I've read in Expert Python Programming about this edge case. Check this code:
def f(arg={}):
arg['3'] = 4
return arg
>>> print f()
{'3': 4}
>>> res = f()
>>> res['4'] = 'Still here'
>>> print f()
{'3': 4, '4': 'Still here'}
It's not clear to me why when f
gets called the last time (after its return value has been saved), instead of assigning arg the empty dict (since it was called with no arguments), it keeps the old reference.
The book says so: "if an object is created within the arguments, the argument reference will still be alive if the function returns the object".
I understand that "this is the way it works", but why so?