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)?
A similar technique can be used to create functions which can deal with an unlimited number of keyword/argument pairs. If an argument to a function is preceded by two asterisks, then inside the function, Python will collect all keyword/argument pairs which were not explicitly declared as arguments into a dictionary.
In Python 3.7 and newer, there is no limit.
Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.
As the argument is an attribute of the function object, it normally has the same lifetime as the function. Usually, functions exist from the moment their module is loaded, until the interpreter exits.
However, Python functions are first-class objects and you can delete all references (dynamically) to the function early. The garbage collector may then reap the function and subsequently the default argument:
>>> def foo(bar, spam=[]):
... spam.append(bar)
... print(spam)
...
>>> foo
<function foo at 0x1088b9d70>
>>> foo('Monty')
['Monty']
>>> foo('Python')
['Monty', 'Python']
>>> foo.func_defaults
(['Monty', 'Python'],)
>>> del foo
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
Note that you can directly reach the func_defaults
attribute (__defaults__
in python 3), which is writable, so you can clear the default by reassigning to that attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With