According to the official documentation, and some stackoverflow answers, the issue in the following code:
def mutable_default(var=[]):
var.append(1)
print(var)
mutable_default([2]) # Output: [2,1]
mutable_default([2]) # Output: [2,1]
mutable_default() # Output: [1]
mutable_default() # Output: [1,1] !!!
is due to default value being evaluated only once, and hence we’re changing the same list, when we call the function.
Let’s do the change the function in the following way:
def mutable_default_with_id(var=[]):
print(f"var before append {var}")
print(f"id(var) -> {id(var)}")
var.append(1)
print(f"var after append {var}")
When I run
mutable_default([2])
mutable_default([3]) # same id as in mutable_default([2])
mutable_default()
mutable_default() # same id as in mutable_default()
mutable_default([3]) # same id as in mutable_default([2])
The ids of var remain the same also for when we pass a list. So it seems that for each case, we’re changing the same object, and hence we need a more specific answer to properly explain what’s happening here.
What’s that?
P.S.: One very popular answer in stackoverflow point to this link. However, the explanation on the link seems to be the same, as before… or maybe I’m interpreting it incorrectly.