I just started learning python, just got struck by the default argument concept.
It is mentioned in python doc that the default argument value of a function is computed only once when the def
statement is encountered. This makes a large difference between values of immutable and mutable default function arguments.
>>> def func(a,L=[]):
L.append(a)
return L
>>> print(func(1))
[1]
>>> print(func(2))
[1, 2]
here the mutable function argument L retains the last assigned value (since the default value is calculated not during function call as like in C)
is the lifetime of the default argument's value in python is lifetime of the program (like static variables in C) ?
Edit :
>>> Lt = ['a','b']
>>> print(func(3,Lt))
['a', 'b', 3]
>>> print(func(4))
[1, 2, 4]
here during the function call func(3,Lt)
the default value of L
is preserved, it is not overwritten by Lt
.
so is default argument have two memory? one for actual default value (with program scope) and other for when an object is passed to it (with scope of function call)?