I just ran across something similar. The as in the except does not behave as expected:
#!/usr/bin/python3.6
exc = 'foofoo'
print('exc in locals?', 'exc' in locals())
try:
x = 1 / 0
except Exception as exc:
print('exc in locals?', 'exc' in locals())
print('Error', exc)
print('exc in locals?', 'exc' in locals())
print('Sorry, got an exception', exc)
This results in the following output. NameError is indicates that exc is no longer in locals().
% ./g.py
exc in locals? True
exc in locals? True
Error division by zero
exc in locals? False
Traceback (most recent call last):
File "./g.py", line 11, in <module>
print('Sorry, got an exception', exc)
NameError: name 'exc' is not defined
%
The as ex removed the the variable from the scope. I have not been found the explanation for this. This code produces the expected output:
#!/usr/bin/python3.6
exc = 'foofoo'
print('exc in locals?', 'exc' in locals())
try:
x = 1 / 0
except Exception as exc_:
exc = str(exc_)
print('exc in locals?', 'exc' in locals())
print('Error, exc)
print('exc in locals?', 'exc' in locals())
print('Sorry, got an exception', exc)
This explains the observed behavior:Python 3 try statement