I was working on a function at work and ran into a variable scoping issue that I'm not sure I fully understand. I have written an example below that replicates the behaviour. Why is it that when I run this function consecutively key-value pairs from previous calls are present in the output?
For reference I'm working with python 3.8.8
def scoping_test(x={}, new_things=[]):
y = x
y.update({thing: 'test' for thing in new_things})
return y
Result after running consecutively.
scoping_test(new_things=['thing1'])
{'thing1': 'test'}
scoping_test(new_things=['thing2'])
{'thing1': 'test', 'thing2': 'test'}
The problem goes away if I explicitly make a copy of the dictionary parameter.
x = dictionary.copy()
I would have expected the function to create a new empty variable x each time the function is called and y is just a reference to x. How is y referencing data from a previous function call?