When you define a function in Python with an array parameter, what is the scope of that parameter?
This example is taken from the Python tutorial:
de
The scope is as you would expect.
The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].
The list is stored in f.func_defaults
.
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
print f.func_defaults
f.func_defaults = (['foo'],) # Don't do this!
print f(4)
Result:
[1]
[1, 2]
[1, 2, 3]
([1, 2, 3],)
['foo', 4]