oneeyedelf1
oneeyedelf1

Reputation: 61

do not understand closures question in python

def a(b=[]):
    b.append(1)
    return b

print a()
print a()

All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.

Thanks for the help

Upvotes: 5

Views: 181

Answers (4)

Corey Goldberg
Corey Goldberg

Reputation: 60604

default arguments are evaluated (once) when the function is defined, not each time it is called.

try this:

def a(b=None):
    if b is None
        b = []     
    b.append(1)
    return b

print a()
print a()

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

The corrected version, for the reasons given in other answers, is:

def a(b=None):
    b = [] if b is None else b

    b.append(1)
    return b

Upvotes: 3

Karl Knechtel
Karl Knechtel

Reputation: 61525

Nothing to do with closures, at least not in the usual sense.

The default value for b is not "a new empty list"; it is "this particular object which I just created right now while defining the function, initializing it to be an empty list". Every time the function is called without an argument, the same object is used.

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of None and check for that instead if you want to get around this.

Upvotes: 10

Related Questions