Why is the empty dictionary a dangerous default value in Python?

tscizzle picture tscizzle · Oct 12, 2014 · Viewed 45.4k times · Source

I put a dict as the default value for an optional argument to a Python function, and pylint (using Sublime package) told me it was dangerous. Can someone explain why this is the case? And is a better alternative to use None instead?

Answer

Bill Lynch picture Bill Lynch · Oct 12, 2014

Let's look at an example:

def f(value, key, hash={}):
    hash[value] = key
    return hash

print f('a', 1)
print f('b', 2)

Which you probably expect to output:

{'a': 1}
{'b': 2}

But actually outputs:

{'a': 1}
{'a': 1, 'b': 2}