Quantcast
Channel: Bart Vanherck
Viewing all articles
Browse latest Browse all 21

Mutable Default Arguments in python

$
0
0

Our team has some simulators and integration tests written in python. For the most part, Python is a simple language that avoid surprises. That is why we took this language as the language used for testing. There are some few situations that can be confusing though. One of the most common surprise are the default arguments. More specific, mutable default arguments.

Suppose you have a function like the following:

def append_to_list(element, a_list=[]):
    a_list.append(element)
    return a_list

Of course, you can call this function with or without any parameters. What happens in the following situation?

my_list = append_to_list(10)
print(my_list)
other_list = append_to_list(20)
print(other_list)

You expect that a new list is created each time the function is called, because the second parameter is not provided. So you expect the following output:

[10]
[20]

But that is not the case. What you see on your console is the following:

[10]
[10, 20]

A new list is created only once. It is only created on definition time of the function and not on calling time like in other languages. This means that if you mutated the object, you also have mutated it for future usages as well.
We should create an object each time the function is called. This can be done by adding another default argument that signals us, that there is no argument provided.

def append_to_list(element, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(element)
    return a_list

And now the output is the one we did expect.


Viewing all articles
Browse latest Browse all 21

Trending Articles