Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
The following code illustrates the issue:
def fn(param, named_param={}, another_named_param=1):
named_param[param] = str(another_named_param)
another_named_param += param
return named_param
for i in range(0, 2):
result = {}
result = fn(i)
print result
print
for i in range(0, 2):
result = fn(i, named_param={})
print result
print
result = fn(0)
print result
result = fn(1)
print result
Output:
{0: '1'}
{0: '1', 1: '1'}
{0: '1'}
{1: '1'}
{0: '1', 1: '1'}
{0: '1', 1: '1'}
I expected the output of the 1st, 2nd loop and subsequent 2 single calls with param matching the values of the for loop would have the same textual output, but fn
holds onto the value of named_param
if not explicitly defaulted to an empty dictionary. Is functionality defined in the documentation?