PyCQA / pyflakes

A simple program which checks Python source files for errors
https://pypi.org/project/pyflakes
MIT License
1.37k stars 179 forks source link

inconsistent behavior with locals(), comprehensions and the unused local variable warning #136

Open pyflakes-bot opened 10 years ago

pyflakes-bot commented 10 years ago

Original report by fawio on Launchpad:


Hi, As far as I know, bug 872503 (#142) was meant to fix the issue of code using locals() not being recognized as using local variables and indeed the code

# No warning
def test():
    a = 5
    return locals()

does not raise any warnings, but I've noticed that using locals() in the context of a comprehension (except a list comprehension) will incorrectly make pyflakes assume that the locals are not being used.

Using code as an example,

# No warning
def test():
    a = 5
    return [i for i in locals().values()]

does not raise a warning but the following generator expression:

# local variable 'a' is assigned to but never used
def test():
    a = 5
    return (i for i in locals().values())

set comprehension:

# local variable 'a' is assigned to but never used
def test():
    a = 5
    return {i for i in locals().values()}

and dict comprehension:

# local variable 'a' is assigned to but never used
def test():
    a = 5
    return {k: v for k, v in locals().items()}

all raise the unused local variable warning, which is pretty inconsistent with the previous behavior.

This is not a hugely critical bug but it's annoying and it could imply some bugs in the comprehensions elsewhere. Thanks for reading.

asottile commented 2 years ago

removing the python2 label -- this is still an issue in python3 -- locals() in the comprehension iterable should target the outer scope rather than the inner scope