[issue17792] Unhelpful UnboundLocalError due to del'ing of exception target

Aaron Smith report at bugs.python.org
Thu Sep 30 15:55:16 EDT 2021


Aaron Smith <aaronwsmith at gmail.com> added the comment:

I encountered the similar behavior unexpectedly when dealing with LEGB scope of names. Take the following example run under Python 3.9.2:

def doSomething():
    x = 10
    del x
    print(x)

x = 5
doSomething()

This produces a UnboundLocalError at print(x) even though "x" can still be found in the global scope. Indeed if your add print(globals()) before the print(x) line, you can see "x" listed.

By contrast, LEGB scope behavior works as expected in this example:

def doSomething():
    print(x)

x = 5
doSomething()

The former example yielding the UnboundLocalError when dealing with name scope feels like a bug that lines up with the original behavior described in this enhancement request, as I believe "x" is still a bounded name in the global scope, but was explicitly deleted from the local scope.

----------
nosy: +aaronwsmith

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue17792>
_______________________________________


More information about the Python-bugs-list mailing list