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

PythonOptional ParametersPylintOptional Arguments

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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}

Solution 2 - Python

It's dangerous only if your function will modify the argument. If you modify a default argument, it will persist until the next call, so your "empty" dict will start to contain values on calls other than the first one.

Yes, using None is both safe and conventional in such cases.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontscizzleView Question on Stackoverflow
Solution 1 - PythonBill LynchView Answer on Stackoverflow
Solution 2 - PythonJohn ZwinckView Answer on Stackoverflow