Skip to content

F841 reports misleading location in try/except block #378

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
andialbrecht opened this issue Oct 30, 2018 · 3 comments
Open

F841 reports misleading location in try/except block #378

andialbrecht opened this issue Oct 30, 2018 · 3 comments

Comments

@andialbrecht
Copy link

In this example pyflakes reports a misleading location for an unused variable:

$ cat example.py 
def foo():
    exc = None
    try:
        print('foo')
    except NameError as exc:
        print(exc)

$ pyflakes example.py 
example.py:5: local variable 'exc' is assigned to but never used

pyflakes reports exc on line 5 (the except line) as unused, which is misleading in my opinion since it's used within the exception handling. I guess that pyflakes recognizes that exc from line 2 (exc = None) as unused (which is unused actually), but determines line 5 as the last occuring declaration of exc.

@asottile
Copy link
Member

Note that this only errors in python3, probably due to the "new" exception scoping rules (except ... as e is roughly equivalent to that block of code; del e):

$ ./venv2/bin/pyflakes t.py
$ ./venv3/bin/pyflakes t.py
t.py:5: local variable 'exc' is assigned to but never used

@g4borg
Copy link

g4borg commented Nov 28, 2018

note that the above code example in python3 will throw a NameError (global scope) or UnboundLocalError (function scope), at least for me in Py3.6.6, if you would actually use exc after that block

exc = None
try:
    raise Exception("Error.")
except Exception as exc:
    print(exc)
print(exc) # raises Error.

interestingly even like this

def testing(exc=None):
    try:
        raise Exception("Error.")
    except Exception as exc:
        print(exc)
    print(exc)

testing() # raises error.
testing('abc') # also raises error.

so i guess flagging it as unused is quite useful info, but even if you would use it, it would not be good.

@asottile
Copy link
Member

#345 is closely related

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants