I have the following code:
def foo():
e = None
try:
raise Exception('I wish you would except me for who I am.')
except Exception as e:
print(e)
print(e)
foo()
In Python 2.7, this runs as expected and prints:
I wish you would except me for who I am.
I wish you would except me for who I am.
However in Python 3.x, the first line is printed, but the second line is not. It seems to delete the variable in the enclosing scope, giving me the following traceback from the last print statement:
Traceback (most recent call last):
File "python", line 9, in <module>
File "python", line 7, in foo
UnboundLocalError: local variable 'e' referenced before assignment
It is almost as if a del e
statement is inserted after the except
block. Is there any reasoning for this sort of behavior? I could understand it if the Python developers wanted except blocks to have their own local scope, and not leak into the surrounding scope, but why must it delete a variable in the outer scope that was previously assigned?