python-3.x - 在包装器中避免 flake8-bugbear 的 B006(即可变默认警告)的预期方法是什么?

标签 python-3.x flake8

我有一个像这样的函数包装器

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/

相关文章:

python - Pandas 数据框 : keep rows with duplicates

pycharm - 使用pyproject.toml定义PyCharm的检查规则

python - 如何阻止 flake8 和 pylint 提示 shebang 线超过最大字符数?

python - 如何修复 flake 8 错误 "E712 comparison to False should be ' 如果 cond 为 False :' or ' 如果不是 cond :'"在 pandas dataframe

Python 在广泛的处理程序中捕获先前的异常

带有波斯语/阿拉伯语字符的 Python 3 print() 函数

python - 如何从文本文件中打印特殊字符

Python——字符串错误

python - 在 PyCharm 中禁用检查

python - 获取 flake8 返回非零代码 : 1 in docker