Sat 8 Apr 2006
Something I discovered/remembered the other day: when you define a Python function with keyword parameters, the default values are only created once, at function compilation-time. Now, since most default values are things like None or integers, this isn’t really a big deal. On the other hand, if the default value you’re supplying is MyClass(5, 6, 7), you might be surprised to discover that the same instance gets used with every function call.
We can exploit this to fake an equivalent to C’s static local variables. Try this:
def foo(item, acc=[]):
acc.append(item)
return acc
Now, call foo a few times with only a single argument.
>>> foo(5) [5] >>> foo(6) [5, 6] >>> foo(7) [5, 6, 7] >>>
I’m sure there are much more interesting uses for this than my contrived little example, but you get the idea.