4 ms·
Also, for the first example, it is a scope issue: def foo2(): def foo(a=[]): a.append('ba') return a return foo() print foo2() print
by kghose 12y ago
Also, for the first example, it is a scope issue:
def foo2():
def foo(a=[]):
a.append('ba')
return a
return foo()
print foo2()
print foo2()
print foo2()
print foo2()
print foo2()
Gives
['ba']
['ba']
['ba']
['ba']
['ba']
- kilink 12y agoI think the way he described it is pretty accurate. Default keyword arguments are only evaluated once at function definition, so supplying a mutable default keyword argument can cause issues. Your example is pretty contrived and doesn't illustrate what he was pointing out, as you're creating a new function foo every time foo2 is called, and only calling it once.