Python Default Parameter Value Gotchas

09/11/2010

Imagine you have a trivial Python function which looks like this:

>>> def x(a=[]):
...     return a
... 
>>> x()
[]

Did you know what happens when you perform destructive operations on the default value which is returned?

>>> x().append(1)
>>> x()
[1]
>>> x().append(2)
>>> x()
[1, 2]

Well, now you do. That default list is only initialized once, not on each call. Please avoid writing code like you'd avoid ebola. Instead consider writing one of these:

# python 2.5+
def x(a=None):
    return a if a else []

# the old but at times reviled syntax
def x(a=None):
    return a or []

# memory usage here is not ideal
def x(a=[]):
    return a[:]

If you've never run into this problem, it's probably because you follow the Python convention of not destructively modifying input without explicit warning. If you're really never done it and aren't simply unaware that you've done it, hooray for you kind sir or madam, hooray for you.

Thanks to Chris Goffinet for explaining this to me after I repeatedly stepped up and down in PDB watching a supposedly empty list enter the function populated.

All Rights Reserved, Will Larson 2007 - 2014.