Reputation: 61
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
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
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
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
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