This is an example from the book "Introducing Python" by Bill Lubanovic illustrating some basics of user-defined functions:
def buggy(arg, result = []):
result.append(arg)
print(result)
buggy('a')
buggy('b')
The "expected" output is a list comprised only of arg
in both cases, but after the second call one gets the list ['a', 'b']
, suggesting that result
is being carried over to the next call. Maybe this isn't surprising, but when I try to print this object it doesn't exist:
In [53]: def buggy(arg, result = []):
....: result.append(arg)
....: print(result)
....:
In [54]: buggy('a')
['a']
In [55]: result
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-55-a5b1e83cd027> in <module>()
----> 1 result
NameError: name 'result' is not defined
In [56]: buggy('b')
['a', 'b']
What exactly is going on here? Is the issue that result
doesn't exist outside the function, but somehow the second call of buggy
"knows" about the result
that was created by the first call and decides to use it as an argument? The author doesn't really explain what's happening.