Be careful with default function arguments

This is a quite common mistake in Python: using mutable types as default function arguments. Lets see how this happens.

First, here is an example of default function arguments with non-mutable types:

As you can see, the bar variable has a different id on each instance, they are in fact, different objects. Now lets see what happens if the default argument is a mutable type, like a list.

Oh, the bar variable is modified on both instances! It has the same id, son they are effectively references to the same object.

Why is this? In Python, default argument values are evaluated only once, when the file is parsed. So, a list object is created, and its reference is used as the default argument to every instance of the class we create.

In order to avoid this we should pass None as the default value and then set bar to the empty list if the passed argument is None:


Leave a Reply