I began to learn about Python perhaps an hour or two ago.
In a Python tutorial, I came across the below text (between lines of equal signs) regarding default function arguments.
This makes no sense to me at all.
What is the scope and lifetime of L? It appears that the scope is within function f, and the lifetime is permanent?
Well, I'll quit trying to suggest all the possibilities. I simply can't think of any kind of implementation that would cause the first version of the function f below to "accumulate" values, while the second version does not accumulate them.
What is happening under the hood? It seems to me that any reasonable implemenation would cause both versions of f to have the same behavior.
===========================================
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
This will print
[1]
[1, 2]
[1, 2, 3]
If you don't want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
=============================================