What is the scope of a defaulted parameter in Python? What is the scope of a defaulted parameter in Python? python python

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 Lprint 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]


The scope of the L variable is behaving as you expect.

The "problem" is with the list you're creating with []. Python does not create a new list each time you call the function. L gets assigned the same list each time you call which is why the function "remembers" previous calls.

So in effect this is what you have:

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

The Python Tutorial puts it this way:

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

and suggests the following way to code the expected behaviour:

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


There's even less "magic" than you might suspect. This is equivalent to

m = []def f(a, L=m):    L.append(a)    return Lprint f(1)print f(2)print f(3)

m is only created once.