Skip to content
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

Python 3 UnboundLocalError not detected when variable referenced after shadowed by exception variable #345

Open
jayvdb opened this issue Jul 18, 2018 · 2 comments
Labels

Comments

@jayvdb
Copy link
Member

jayvdb commented Jul 18, 2018

For

def a():
    e = 1
    try:
        raise RuntimeError('forced error')
    except Exception as e:
        print(e)
    print(e)

a()

In both Python 2 and 3, exception variable e shadows the local variable e, and is not being reported.

In python3, e is unbound after the exception block, and a UnboundLocalError occurs when the local variable e is referenced because it was disappeared.

@jayvdb jayvdb added the python3 label Jul 18, 2018
@jayvdb
Copy link
Member Author

jayvdb commented Jul 18, 2018

Note this was raised a lot at #59 , but the issue of shadowing wasnt considered.

The following does not raise an error UnboundLocalError on Python 3 ; instead e is 1 after the exception block.

def a():
    e = 1

    try:
        pass
    except Exception as e:
        print(e)

    print(e)

a()

As we can not know whether the try block will pass or which exception might fail, we can not know which local variables were discarded.

Thus the shadowing actually results in very non-deterministic behaviour, and should be considered a bug.

@jayvdb
Copy link
Member Author

jayvdb commented Jul 18, 2018

Note solving this, especially with python2 support, may depend on solving at least parts of #236 first, which puts it in the moderately hard bucket.
While shadowing is problematic, it is relatively common on python 2 to start with e = None followed by multiple try blocks to re-use the same exception name e and then some reporting to occur at the end if any of them assigned a value to e.
Solving it only for python 3 is quite a bit easier.

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

No branches or pull requests

1 participant