为什么空字典是 Python 中危险的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26320899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:21:44  来源:igfitidea点击:

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

pythonoptional-parameterspylintoptional-arguments

提问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 Noneinstead?

我将 dict 作为 Python 函数的可选参数的默认值,pylint(使用 Sublime 包)告诉我这很危险。有人可以解释为什么会这样吗?是更好的替代品None吗?

采纳答案by John Zwinck

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 Noneis both safe and conventional in such cases.

是的,None在这种情况下使用既安全又传统。

回答by Bill Lynch

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}