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 = []
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.
source share