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

对着背影说爱祢 提交于 2019-12-03 04:39:18

问题


I put empty braces 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?


回答1:


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.




回答2:


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}


来源:https://stackoverflow.com/questions/26320899/why-is-the-empty-dictionary-a-dangerous-default-value-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!