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

1

10

Please consider the following example, which finds the first String in a list that contains the Substring "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)

The code works as intended and outputs "JOHN", but I am getting the following warning from flake8 at the line word = match.group(0):

F821 -- undefined name 'match'

Why is this happening, and can I remove the warning without command line arguments or disabling all F821 errors?

Sale answered 15/5, 2021 at 13:19 Comment(10)
Try flake8 --disable-noqa or flake8 --ignore=F821 should work.Leery
what version of flake8 are you using?Centrum
@Centrum flake8 3.9.2 (mccabe: 0.6.1, pycodestyle: 2.7.0, pyflakes: 2.3.1) CPython 3.9.5 on WindowsSale
@Leery as I put in my last paragraph, I'd rather not ignore all F821 warnings.Sale
@Paul My gut feeling says the flake8 has no ability to recognize the new variable assignment introduced in Python3.8. So either you have to wait until the feature introduced or change the code to use old-style or manually ignore those statements.Leery
@Leery Thank you, you're probably right.Sale
it says that newest versions should support the walrus operator, and you have the newest versions of these packagesCentrum
@Centrum Can you try to reproduce the issue? Maybe it's only on my side.Sale
have you tried adding an inline comment noqa: F821 next to the line? word = match.group(0) # noqa: F821 ? like soHenn
@Henn If the condition fails, then match.group(0) is never called, so that shouldn't cause a warning. The inline comment removes the warning, thank you for that.Sale
P
16

This is a bug in pyflakes -- I'd suggest reporting it there

The subtlety is that assignment expressions break out of comprehension scopes, but pyflakes assumes that comprehension scopes enclose all assignments

I'd suggest reporting an issue here

as a workaround, you can place a # noqa comment on the line which produces the error, for example:

# 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

disclaimer: I'm the maintainer of flake8 and one of the maintainers of pyflakes

Photic answered 15/5, 2021 at 14:58 Comment(1)
For future readers: the fix for this has been merged with this PR --> github.com/PyCQA/pyflakes/pull/698Sulfonmethane

© 2022 - 2024 — McMap. All rights reserved.