Fix Python – Why is the empty dictionary a dangerous default value in Python? [duplicate]

Question

Asked By – tscizzle

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?

Now we will see solution for issue: Why is the empty dictionary a dangerous default value in Python? [duplicate]


Answer

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.

This question is answered By – John Zwinck

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0