Posts Tagged ‘lists’

Using mutable objects as default parameter in Python

July 22, 2009

We just came across a weird Python behaviour (of course only weird if you don’t know why). If you use mutable objects such as lists as the default parameter in a function declaration, you might end up with some unintented behaviour. Everytime the function modifies the object, the default value is in effect modified as well (e.g. appending to the list). This is also explained in the Python documentation:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, …

Find the whole thing here.