为什么 flake8 给出警告 F821 -- undefined name 'match' when using match.group(0) with Python 3

Why does flake8 give the warning F821 -- undefined name 'match' when using match.group(0) with Python 3

请考虑以下示例,它在包含子字符串“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”,但我在 word = match.group(0):

行收到来自 flake8 的以下警告
F821 -- undefined name 'match'

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

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

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

我建议报告问题 here

作为解决方法,您可以在产生错误的行上添加 # 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 的维护者之一