我有一个像这样的函数包装器
def fun(arg, kwarg=None): # in my code the function is imported from a package
return None
def mywrap(myarg, funkwargs={"kwarg": "default"}):
return fun(myarg, **funkwargs)
如果我运行包含 Bugbear 的 flake8,我会收到 B006 警告:
$ flake8 above_example.py
above_example.py:5:29: B006 Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them.
在上面的例子中,我想为 fun
提供一些默认设置,这样做的预期方法是什么?
版本:
$ flake8 --version
3.7.9 (flake8-bugbear: 19.8.0, mccabe: 0.6.1, pycodestyle: 2.5.0, pyflakes: 2.1.1) CPython 3.7.3 on Linux
编辑:
如果答案是“使用 None
”,下面的方法是否“正确”?
def mywrap(myarg: Any, funkwargs: Optional[Dict[Any, Any]]=None) -> None:
"""MyWrap.
Parameters
----------
myarg : Any
funkwargs : Dict[Any, Any], Optional
Default `{"kwarg": "default"}`.
"""
if not funkwargs:
funkwargs = {"kwarg": "default"}
return fun(myarg, **funkwargs)
最佳答案
“正确”答案是 types.MappingProxyType
.这会在原始词典上创建一个只读 View 。
def mywrap(myarg, funkwargs=types.MappingProxyType({"kwarg": "default"})):
return fun(myarg, **funkwargs)
比使用 None
作为默认值要好得多。
关于python-3.x - 在包装器中避免 flake8-bugbear 的 B006(即可变默认警告)的预期方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425124/