Friday, August 21, 2015

Python Basics - 012 Dynamic Argument Count

Previous chapter: Intro to Functions Next Chapter: Classes and Objects



Python Basics - 012: Dynamic Argument Count


Functions in python take a variable number of arguments if specified using the * operator, let's look at an example:


def hellotoMany(name1, *others):
    print("Hello", name1)
    for eachname in others:
        print("hello ", eachname)

hellotoMany("Alan", "Jack", "Arya", "Jon")

As we can see in the example above a * before an argument name will give let you give however many arguments to the functions and that will act as a tuple of objects inside the function.

Hence output of that will be:


Hello Alan
hello  Jack
hello  Arya
hello  Jon

The same can be done with keyword arguments, if you remember from last chapter, keyword arguments have the name of the arguments along with their values while calling them. So dynamic keyword arguments can be defined using ** operator. Here's an example of that:


def hellotoManyMore(name1, **kwargs):
    print("Hello", name1)
    print("Hello", kwargs.get('name2'))
    print("Hello", kwargs.get('name3'))

hellotoManyMore("Alan", name3="Jack", name2="Jon")

The output will be as expected,


Hello Alan
Hello Jon
Hello Jack

This will let us retain or mess with the order of arguments when calling the function.

The convention is usually *args and **kwargs, but you can use whatever meets your fancy.

Here's a more thought out example snippet:


def doSomething(first, second, third, **kwargs):
    if kwargs.get("action") == "sum":
        print("The sum is: %d" % (first + second + third))

    if kwargs.get("number") == "second":
        return second

result = doSomething(1, 2, 3, number="second")
print("1. Result: %d" % result)
result = doSomething(1, 2, 3, action="sum", number="second")
print("2. Result: %d" % result)

The above program tries to print a sum if the action parameter is passed and return the second element. If the action argument is not passed then the if condition regarding the action statement is false and the subsequent print() is not executed. Hence the output of the above snippet is:


1. Result: 2
The sum is: 6
2. Result: 2

We can see the optional parameters are indeed optional and even if we use them inside the function it is not throwing an error.

Let's learn about the variables and how they behave in different scopes in the next chapter.


P.S: all the code used in this tutorial is available in github


References:

  1. http://www.learnpython.org/en/Multiple_Function_Arguments
  2. https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
  3. https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments



Previous chapter: Intro to Functions Next Chapter: Classes and Objects

No comments:

Post a Comment