Mutable Default Arguments in python

Mutable Default Arguments in python

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:

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

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:

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

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.

And now the output is the one we did expect.