python - "except Foo as bar"导致 "bar"从范围中删除

标签 python python-3.x scoping

给定以下代码:

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 if

except 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/

相关文章:

python - 我如何让敌人死后掉落金钱?

Python 适合原型(prototype)制作而不适合大规模部署吗?

python - 如何将具有相同名称的列表元素分组?

javascript - 尝试在 Fancybox 回调中调用 CoffeeScript 方法时出现范围问题

确定事件处理程序范围的 JavaScript 最佳实践

python - 新手,对原始的网络表单感到困惑

python 导入错误: No module named package

python - 当我在 python 中将 <class 'pandas.core.frame.DataFrame' > 作为参数发送时,为什么我在方法中收到多个值

python - Scapy:使用 get_trace() 方法索引跟踪路由结果返回 TypeError

Javascript - 在没有类型声明的情况下声明的匿名函数,它们应该是局部范围的吗?