I just started learning python, just amazed at the concept of default arguments.
The python document states that the default argument value for a function is evaluated only once when the def statement is encountered. This makes a big difference between the values ββof immutable and mutable function arguments by default.
>>> def func(a,L=[]): L.append(a) return L >>> print(func(1)) [1] >>> print(func(2)) [1, 2]
here the argument of the mutable function L stores the last assigned value (since the default value is not calculated during the function call, as in C)
is the lifetime of the default argument value in python - is this the lifetime of the program (e.g. static variables in C)?
Edit:
>>> Lt = ['a','b'] >>> print(func(3,Lt)) ['a', 'b', 3] >>> print(func(4)) [1, 2, 4]
here, when the func(3,Lt) function is called func(3,Lt) default value of L saved, it is not overwritten by Lt
so does the default argument have two memories? one for the actual default value (with the program area) and another for when the object was passed to it (with the scope of the function call)?
source share