I came across a weird difference with local variable scopes between Python 2.7 and Python 3.7.
Consider this artificial script unboundlocalexception.py
(I realize that I could just have used an else-block after except, but I extracted this example from a longer function):
def foo():
arithmetic_error = None
try:
y = 1.0 / 0
except ZeroDivisionError as arithmetic_error:
print("I tried to divide by zero")
if arithmetic_error is None:
print("Correct division")
foo()
Under Python 2 it works as I expected it to:
$ python2 unboundlocalexception.py
I tried to divide by zero
But, surprisingly, under Python 3 an UnboundLocalError is raised!
$ python3 unboundlocalexception.py
I tried to divide by zero
Traceback (most recent call last):
File "unboundlocalexception.py", line 11, in <module>
foo()
File "unboundlocalexception.py", line 8, in foo
if arithmetic_error is None:
UnboundLocalError: local variable 'arithmetic_error' referenced before assignment
Is this difference documented anywhere?