给定以下代码:
msg = "test"
try:
"a"[1]
except IndexError as msg:
print("Error happened")
print(msg)
有人可以解释为什么这会导致 Python 3 中出现以下输出吗?
Error happened
Traceback (most recent call last):
File "test.py", line 6, in <module>
print(msg)
NameError: name 'msg' is not defined
最佳答案
except 子句中的
msg
与第一行的 msg
范围相同。
但是in Python 3 we have this new behavior too :
When an exception has been assigned using
as target
, it is cleared at the end of the except clause. This is as ifexcept E as N: foo
was translated to
except E as N: try: foo finally: del N
This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.
所以,你在异常处理程序中“覆盖msg
”,退出处理程序将删除变量以清除回溯引用循环。
关于python - "except Foo as bar"导致 "bar"从范围中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52965952/