Fork me on GitHub

Project Notes

#060 Quirks - Mutable Default Arguments

python quirks and gotchas

Notes

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=[]):
    to.append(element)
    return to
print append_to(1)
[1]
append_to(1)
[1, 1]
append_to(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 mutable_default_params.py for a test of the problem and the fix.

$ ./mutable_default_params.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Credits and References

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

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.

LittleArduinoProjects LittleModelArt More on my blog