I am trying to understand how functions internally store the value for default arguments.
I thought it was stored into the attribute __defaults__
of the function object. However this attribute seems to store a copy of the objects value (the list value), and not the reference of the object itself.
# I declare a list and defines it as the default argument value for my_function
>>> my_list = [1,2,3]
>>> def my_function(value=my_list):
... print(my_list)
...
# the call to "my_function" displays the value of "my_list"
>>> my_function()
[1, 2, 3]
# The modification of "my_list" affects the results displayed by "my_function"
>>> my_list.append(4)
>>> my_function()
[1, 2, 3, 4]
# The tuple storing my_function default arguments seems to store the value of "my_list"
# but not its reference (my_list identity)
>>> my_function.__defaults__
([1, 2, 3, 4],)
If my_function.__defaults__
was the only copy made, the edition of my_list
should not modify the behavior of the function. However, this affects the function behavior which shows that the function object stores the reference of my_list
somehwhere (and not only the value).
Could you please explain me how it is done ?