Python default function argument lifetime

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)?

+4
source share
2 answers

Since an argument is an attribute of a function object, it usually has the same lifetime as the function. Usually, functions exist from the moment the module is loaded until the translator exits.

However, Python functions are first-class objects, and you can remove all references (dynamically) to a function earlier. Then the garbage collector can use the function, and then 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 func_defaults attribute ( __defaults__ in python 3), which is writable, so you can clear the default value by reassigning this attribute.

+10
source

It has at least the same lifetime as the function object (something funky is missing). Accordingly, if the module from which it was loaded is unloaded by all other modules, and there are no other links, then the function object and its members are most likely to be destroyed.

Since Python is garbage collection, you do not need to worry about it in any practical sense. If the object escapes, and in some other part of the program there is a link, it will freeze.

If you want you to rely on an object hanging around and not reset, then yes, you can do it if you don’t have something funky unloading module, or if you have code that assigns a variable to a function object that saves the default value.

+3
source

Source: https://habr.com/ru/post/1480777/


All Articles