Alex Rivera | Logout

What is the scope of a defaulted parameter in Python?

Asked 2010-02-25T15:26:36.240
34

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:

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

print f(1)
print f(2)
print f(3)

Prints:

[1]
[1, 2]
[1, 2, 3]

I'm not quite sure if I understand what's happening here. Does this mean that the scope of the array is outside of the function? Why does the array remember its values from call to call? Coming from other languages, I would expect this behavior only if the variable was static. Otherwise it seems it should be reset each time. And actually, when I tried the following:

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

I got the behavior I expected (the array was reset on each call).

So it seems to me that I just need the line def f(a, L=[]): explained - what is the scope of the L variable?

Edit
Report

2 Answers

2

Say you have the following code:

def func(a=[]):
    a.append(1)
    print("A:", a)

func()
func()
func()

You can use python's indentation to help you understand what's going on. Everything that is flush to the left margin is executed when the file gets executed. Everything that's indented is compiled into a code object which gets executed when func() is called. So the function is defined and its default arguments set once, when the program gets executed (because the def statement is flush left).

What it does with the default arguments is an interesting issue. In python 3, it puts most of the information about a function in two places: func.__code__ and func.__defaults__. In python 2, func.__code__ was func.func_code func.__defaults__ was func.func_defaults. Later versions of python 2, including 2.6 have both sets of names, to aid the transition from python 2 to python 3. I will use the more modern __code__ and __defaults__. If you're stuck on an older python, the concepts are the same; just the names differ.

The default values are stored in func.__defaults__, and retrieved each time the function is called.

Thus when you define the function above, the body of the function gets compiled and stored in variables under __code__, to be executed later, and the default arguments get stored in __defaults__. When you call the function, it uses the values in __defaults__. If those values get modified for any reason, it only has the modified version available to use.

Play around defining different functions in the interactive interpreter, and see what you can figure out about how python creates and uses functions.

answered 2010-02-25T16:31:39.777
1

The explaination is given in answers to this question. To sum it up here:

Functions in Python are a kind of object. Because they are a kind of object, they act like objects when instantiated. A function, if defined with a mutable attribute as a default argument, is exactly the same as a class with a static attribute that is a mutable list.

Lennart Regebro has a good explanation and the answer to the question by Roberto Liffredo is excellent.

To adapt Lennart's answer ... if I have a BananaBunch class:

class BananaBunch:
    bananas = []

    def addBanana(self, banana):
        self.bananas.append(banana)


bunch = BananaBunch()
>>> bunch
<__main__.BananaBunch instance at 0x011A7FA8>
>>> bunch.addBanana(1)
>>> bunch.bananas
[1]
>>> for i in range(6):
    bunch.addBanana("Banana #" + i)
>>> for i in range(6):
    bunch.addBanana("Banana #" + str(i))

>>> bunch.bananas
[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5']

// And for review ... 
//If I then add something to the BananaBunch class ...
>>> BananaBunch.bananas.append("A mutated banana")

//My own bunch is suddenly corrupted. :-)
>>> bunch.bananas
[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5', 'A mutated banana']

How does this apply to functions? Functions in Python are objects. This bears repeating. answered 2010-02-25T15:40:16.207

Your Answer