Function Arguments Python

Python Gotcha: Mutable Default Arguments

  • gotcha

    • counterintuitive feature of a programming language

    • something that doesn’t make sense at a first glance

  • mutable object

    • various containers intended to be changed

    • when using mutable objects in function arguments, the function is only created once and anytime we try to access it, the same mutable object is being modified

Variable Number of Arguments - *args

  • unpacking operator ()*

    • Allows us to give functions a variable number of arguments by performing positional argument packing

    • Name follows the (*) will store the passed arguments into the function in a tuple

def my_function(*args):
print(args)
# Calling the function
my_function('Arg1', 245, False)

Working with *args

  • (*) not limited to being used alone, can be combined with various positional arguments

    • Utilizing iteration and other positional arguments are two common ways we can increase the utility of our functions when using the unpacking operator (*)

def truncate_sentences(length, *sentences):
for sentence in sentences:
print(sentence[:length])
# Callin the function
truncate_sentences(8, 'What\'s going on here', 'Looks like we\'ve been cut off'

Variable Number of Arguments - **kwargs

  • also allows us to define functions with unlimited keyword arguments

  • syntax - (**)

    • (**) takes the form of a dictionary with all the passed keyword arguments

def arbitrary_keyword_args(**kwargs):
print(type(kwargs))
print(kwargs)
# Seeing if 'anything goes' is an argument
print(kwargs.get('anything goes'))
# Calling the function
arbitrary_keyword_args(this_arge='wowzers', anything_goes=101)

Working with **kwargs

  • Because (**) uses a standard dictionary, we can utilize iteration

  • We can use positional arguments with (**), but must come first in our function definition

def print_data(positional_arg, **data):
print(positional_arg)
for arg in data.values():
print(arg)

print_data('position 1', a='arg1', b=True, c=100)

Combining () & (*)

  • Python allows us to use this specific order in our function defintion:

    1. Standard Positional Arguments

    2. *args

    3. Standard Keyword Arguments

    4. **kwargs

def print_animals(animal1, animal2, *args, animal4, **kwargs):
print(animal1, animal2)
print(args)
print(animal4)
print(kwargs)

Function Call Unpacking & Beyond

num_list = [3, 6, 9]
def sum(num1, num2, num3):
print(num1 + num2 + num3)
sum(*num_list)

robot