Complementing the william’s response, in fact, what occurs is the evaluation of the arguments in time of method definition and how the objects in Python are treated as reference, in the method definition is created an object that represents the default value and in each new instance (or method call)the parameter will point to that same instance. This explains why the return of id
is the same for different instances and becomes even clearer when analyzing the attribute __defaults__
of the method.
According to the documentation, the attribute __defaults__
is a tuple that contains the default values of the arguments of a function or method. In this case, considering the code presented in the question:
class Foo:
def __init__(self, values = []):
self.values = values
We can verify the value of __defaults__
of the initialising method:
print(Foo.__init__.__defaults__) # ([],)
The first value of this tuple is a mutable object that represents the default value of the argument values
, existing since the definition of the class, since, in Python, the class itself is an object - and the method is also an object.
When checking the return of id
of this object is confirmed that it represents the same reference of a.values
and b.values
:
print(id(Foo.__init__.__defaults__[0])) # 47568867296648
To confirm all that has been said in practice, just check the value in __defaults__
after an instance of Foo
which has its modified class attribute:
print(Foo.__init__.__defaults__) # ([],)
a = Foo()
a.values.append(1)
print(Foo.__init__.__defaults__) # ([1],)
That is, when creating an instance and modifying its instance attribute, this attribute being the mutable type, the object itself representing the default value of the argument, stored in __defaults__
, is modified equally.
See working on Ideone.
A similar question was asked in Stack Overflow:
Why are default Arguments evaluated at Definition time in Python
Float is a changeable or immutable type in Python? This happens with floats as well?
– Thiago Krempser
Very useful this tip: "it is recommended not to make use of mutable objects as default values in function settings, use None instead and deal within function".
– Thiago Krempser
Good night dear @Thiagokrempser, numbers refers to the float and the integers, are also immutable. Thanks for the editing, it was a great contribution.
– Guilherme Nascimento