What Happens When I Reassign The Mutable Default Argument Inside A Function?
Solution 1:
Let's rewrite your example so that we make some change to the argument before reassigning:
In [262]: def foo(var=[]):
...: var.append(1) # 1
...: print(var) # 2
...: var = [] # 3
...: return var # 4
...:
In [263]: foo()
[1]
Out[263]: []
In [264]: foo()
[1, 1] # reflects the append from the previous call
Out[264]: []
The append step in line 1 mutates the default argument list. The reassignment step in line 3 simply reassigns the variable var
to a new list (a completely different object), that's what you return.
You'll see each subsequent call modifies the default argument list, it's still there but you just don't see it because you lose the reference to it when you reassign.
I recommend reading this article by Ned Batchelder.
Solution 2:
alright, so the two things:
var
in your function definition is assigned to an empty list i.e[]
that is good,var
in theif
statement is again being re-assigned but is the same thing, an empty list, this you don't really need as it's preventing you from achieving[1,1]
this may help clear things of why you're "expecting" a var = [1,1]
the first time around:
def foo(var=[]):
if len(var) == 0:
print(var)
var.append(1)
return var
print(foo()) # returns [],[1]
print(foo()) # returns [1,1] this list appended another 1 in because when you ran this instance of foo, this list was not empty anymore rather filled with 1 and bypassed the if statement and appended another 1 resulting to [1,1]
thus, you don't really need that var = []
in the if statement as it confuses the next steps as to what you want to achieve...
hope that helps somewhat :)
Solution 3:
var=[]
on line 1 gets evaluated once when the function is defined
var=[]
on line 3 gets evaluated every time you pass a var with len(var) == 0
, for instance when you pass no args and the default is used.
This means that the []
on line 3 is a new list every time the function is called, as that line of code is executed every time the function is called.
Post a Comment for "What Happens When I Reassign The Mutable Default Argument Inside A Function?"