Python Default Parameter Value Gotchas
python (59)Imagine you have a trivial Python function which looks like this:
>>>defx(a=[]):...returna...>>>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+defx(a=None):returnaifaelse[]# the old but at times reviled syntaxdefx(a=None):returnaor[]
# memory usage here is not idealdefx(a=[]):returna[:]
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 simplyunawarethat you've done it, hooray for you kind sir or madam, hooray for you.
Thanks toChris Goffinetfor explaining this to me after I repeatedly stepped up and down in PDB watching a supposedly empty list enter the function populated.