What is the scope of a defaulted parameter in Python?

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.__defaults__ (or f.func_defaults in Python 2.)

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)
print f.__defaults__
f.__defaults__ = (['foo'],) # Don't do this!
print f(4)

Result:

[1]
[1, 2]
[1, 2, 3]
([1, 2, 3],)
['foo', 4]

Leave a Comment