Certified Python Developer Learning Resources VarArgs and keyword-only parameters

Learning Resources
 

VarArgs and keyword-only parameters


VarArgs parameters

Sometimes you might want to define a function that can take any number of parameters, this can be achieved by using the stars:

#!/usr/bin/python
# Filename: total.py
 
def total(initial=5, *numbers, **keywords):
    count = initial
    for number in numbers:
        count += number
    for key in keywords:
        count += keywords[key]
    return count
 
print(total(10, 1, 2, 3, vegetables=50, fruits=100))

Output:

   $ python total.py
   166

How It Works:

When we declare a starred parameter such as *param, then all the positional arguments from that point till the end are collected as a tuple called 'param'.

Similarly, when we declare a double-starred parameter such as **param, then all the keyword arguments from that point till the end are collected as a dictionary called 'param'.

Keyword-only Parameters

If we want to specify certain keyword parameters to be available as keyword-only and not as positional arguments, they can be declared after a starred parameter:

#!/usr/bin/python
# Filename: keyword_only.py
 
def total(initial=5, *numbers, extra_number):
    count = initial
    for number in numbers:
        count += number
    count += extra_number
    print(count)
 
total(10, 1, 2, 3, extra_number=50)
total(10, 1, 2, 3)
# Raises error because we have not supplied a default argument value for 'extra_number'

Output:

   $ python keyword_only.py
   66
   Traceback (most recent call last):
     File "keyword_only.py", line 12, in 
   total(10, 1, 2, 3)
   TypeError: total() needs keyword-only argument extra_number

How It Works:

Declaring parameters after a starred parameter results in keyword-only arguments. If these arguments are not supplied a default value, then calls to the function will raise an error if the keyword argument is not supplied, as seen above.

Notice the use of += which is a shortcut operator, so instead of saying x = x + y, you can say x += y.

If you want to have keyword-only arguments but have no need for a starred parameter, then simply use an empty star without using any name such as def total(initial=5, *, extra_number).

-Swaroopch
 For Support