Mutable Default Arguments in Python
Giving your functions defaults to work off of
Objects of built-in types like int, float, bool, str, tuple, and Unicode are immutable. Objects of built-in types like list, set, and dict are mutable. A mutable object can change its state or contents, whereas immutable objects cannot.
This is a very simple definition of mutable and immutable objects in Python. Now for the interesting part, which is a mutable default object in function definitions.
I have written a very simple function below:
def foobar(element, data=[]):
data.append(element)
return dataIn this function, I set data to a list (mutable object) as a default argument. Now let's execute this function:
>>> print(foobar(12))
[12]The output is as expected. Now execute multiple times:
>>> print(foobar(22))
[12, 22]
>>> print(foobar(32))
[12, 22, 32]What is going on here? As you can see, the first time, the function returns exactly what we expected. On the second and all subsequent passes, the same list is used in each call.
Why Is This Happening?
Python’s default arguments are evaluated once when the function is defined — not each time the function is called. When Python encounters it, the first thing it will do is compile it in order to create a code object for this function. While this compilation step is done, Python evaluates and then stores the default arguments in the function object itself.
So let’s do some introspection. To clear up any confusion, I have highlighted a few lines of code.
Function before execution
def foo(l=[]):
l.append(10)After the function executes this definition, you can check the default attribute for this function by using __defaults__.
Get Prashant Sharma’s stories in your inbox
Join Medium for free to get updates from this writer.
__defaults__ is a tuple containing default argument values for those arguments that have defaults (or None if no arguments have a default value).
>>> foo.__defaults__
([],)The result is an empty list as the only entry in __defaults__.
Function after execution
Let’s now execute this function and check the defaults:
>>> foo()
>>> foo.__defaults__
([10],)Astonished? The value inside the object changes. Consecutive calls to the function will now simply append to that embedded list object.
Let’s execute the function multiple times:
>>> foo()
>>> foo()
>>> foo()>>> foo.__defaults__
([10, 10, 10, 10],)
This is happening because default argument values are stored in the function object and not the code object (since they represent values calculated at runtime).
The Solution
Now, the question is how to code foobar in order to get the behavior that we expected.
Fortunately, the solution is straightforward. The mutable objects used as defaults are replaced by None and then the arguments are tested for None:
def foobar(element, data=None):
if data is None:
data = []
data.append(element)
return data>>> foobar(12)
[12]
So replacing mutable default arguments with None solved our problem.
Good Use of Mutable Default Argument
However, mutable default arguments also have some good use cases:
- Binding a local variable to the current value of the outer variable in a callback.
- Cache/memoization.
Conclusion
I hope you liked this explanation of mutable default arguments in Python. If you have any doubts or questions, let me know in the comments below.










