If I define a default list parameter like so:
def foo(a, my_list=[]):
my_list.append(a)
return my_list
Then each successive call to foo() without passing the default parameter will append the element to this "hidden" list that seems to persist between calls.
print(foo('a'))
print(foo('b'))
print(foo('c'))
This prints:
['a']
['a', 'b']
['a', 'b', 'c']
Why is this happening? This seems like an antipattern. To avoid this, I have to add the following trick:
def foo(a, my_list=None):
if my_list is None:
my_list = []
my_list.append(a)
return my_list