Variable scope in case of an exception in python

时光总嘲笑我的痴心妄想 提交于 2020-04-13 03:39:11

问题


while True:
  try:
    2/0
  except Exception as e:
    break

print e      

Gives: integer division or modulo by zero

I thought scope of e is within the while block and it will not be accessible in the outside print statement. What did I miss ?


回答1:


Simple: while does not create a scope in Python. Python has only the following scopes:

  • function scope (may include closure variables)
  • class scope (only while the class is being defined)
  • global (module) scope
  • comprehension/generator expression scope

So when you leave the while loop, e, being a local variable (if the loop is in a function) or a global variable (if not), is still available.

tl;dr: Python is not C.




回答2:


in except ... as e, the e will be drop when Jump out of try except, Whether or not it was defined before.

When an exception has been assigned using as target, it is cleared at the end of the except clause.

refer to offical website link: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement




回答3:


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



来源:https://stackoverflow.com/questions/39923315/variable-scope-in-case-of-an-exception-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!