Python default parameter

I was just starting to learn Python, and I got confused in this example:

def append_to(element, to=None): if to is None: to = [] to.append(element) return to 

If to was initialized once, will not to not be None the second time it is called? I know that the code above works, but cannot wrap around this description of "initialized once".

+5
source share
3 answers

If "to" was initialized once, would not "to" not be "None" the second time it was called?

to will become None if you do not pass it a value: append_to(1) and only when to is None , your code will double-check the local name to in the newly created list inside your function body: to = [] .

The default values โ€‹โ€‹for functions are assigned only once, which, regardless of what you set as the default value, this object will be used for every call you make for this function and will not change, usually the same link default values โ€‹โ€‹will be used for every call you make for this function. This matters if you assign mutables by default:

 l = [] def defArgs(d=l) # default arguments, same default list for every call d.append(1) return d defArgs() is l # Object identity test: True 

Run the above function several times, and you will see that the list grows with a lot of elements, because you get only one copy of the default arguments for each function shared by each function call. But notice here:

 def localVars(d=None): if d is None: d = [] # Different list for every call when d is None 

d = [] is executed every time you call localVars ; when the function finishes its task, each local variable collects garbage, when the number of links decreases to 0, but the default values โ€‹โ€‹of the arguments, they live after the function is executed and usually are not collected using the garbage after the function is executed.

+1
source
 def append_to(element, to=None): to = ... 

to here it becomes a local variable and is assigned to the list and removed if you do not assign the return value of another variable.

If you want to stay alive for subsequent calls to append_to , you must:

 def append_to(element, to=[]): to.append(element) return to 

Demo:

 >>> lst = append_to(5) >>> append_to(6) >>> append_to(7) >>> print lst [5, 6, 7] 
+2
source

In Python, there is no declaration and initialization step when you use a variable. Instead, the entire assignment is a definition in which you bind an instance to a variable name.

The interpreter associates the instance with the default value when creating the instance of the function. When the default value is a mutable object, and you change its state only according to your methods, than the value will be "shared" between calls.

0
source

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


All Articles