Fork me on GitHub

Project Notes

Python Quirks - Mutable Default Arguments

python quirks and gotchas


This is one of the classic gotchas detailed in the python-guide.

Default arguments are a hugely common pattern for simplifying function calling requirements. But because they so commonly used, it’s quite a risk that problems like this lurk in the code we write:

def append_to(element, to=[]):
    return to
print append_to(1)
[1, 1]
[1, 1, 1]

wtf? What’s worse, a unit tests that called the function once would think it’s all green.

The problem here is that Python evaluates default parameters at the point the function is defined, not when it is called. This is unlike most other languages like Ruby.

So every time the function is called and using default parameters, the function will get a reference to the same list created when the function was defined.

A list is used here as an example, but this behaviour will be similar for any other type that is passed by reference.

A common fix is to set None as the default value, and correctly initialise the argument’s default value within the function if it is None.

See for a test of the problem and the fix.

$ ./
Ran 2 tests in 0.000s


Credits and References

About LCK#54 python
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.