首页 > 解决方案 > 为什么 flake8 在 Python 3 中使用 match.group(0) 时会给出警告 F821 -- undefined name 'match'

问题描述

请考虑以下示例,该示例在包含子字符串“OH”的列表中查找第一个字符串:

list = ["STEVE", "JOHN", "YOANN"]
pattern = re.compile(".*%s.*" % "OH")
word = ""

if any((match := pattern.match(item)) for item in list):
    word = match.group(0)
print(word)

该代码按预期工作并输出“JOHN”,但我在该行从 flake8 收到以下警告word = match.group(0)

F821 -- undefined name 'match'

为什么会发生这种情况,我可以在没有命令行参数或禁用所有 F821 错误的情况下删除警告吗?

标签: pythonpython-3.xregexflake8

解决方案


这是pyflakes中的一个错误——我建议在那里报告它

微妙之处在于赋值表达式超出了理解范围,但 pyflakes 假设理解范围包含所有赋值

我建议在这里报告问题

作为一种解决方法,您可以# noqa在产生错误的行上添加注释,例如:

# this one ignores *all* errors on the line
word = match.group(0)  # noqa
# this one ignores specifically the F821 error
word = match.group(0)  # noqa: F821

免责声明:我是 flake8 的维护者,也是 pyflakes 的维护者之一


推荐阅读