Python 3 异常删除封闭范围内的变量,原因不明

标签 python exception python-3.x exception-handling

<分区>

我有以下代码:

def foo():
    e = None
    try:
        raise Exception('I wish you would except me for who I am.')
    except Exception as e:
        print(e)
    print(e)

foo()

在 Python 2.7 中,这按预期运行并打印:

I wish you would except me for who I am.
I wish you would except me for who I am.

但是在 Python 3.x 中,第一行被打印出来,第二行没有。它似乎删除了封闭范围内的变量,从最后一个打印语句中给我以下回溯:

Traceback (most recent call last):
  File "python", line 9, in <module>
  File "python", line 7, in foo
UnboundLocalError: local variable 'e' referenced before assignment

这几乎就像是在 except block 之后插入了一个 del e 语句。这种行为有什么理由吗?如果 Python 开发人员希望 except block 具有自己的本地作用域,而不泄漏到周围的作用域,我可以理解,但为什么它必须删除先前分配的外部作用域中的变量?

最佳答案

引用documentation of try ,

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.

这在这两个 PEP 中都有介绍。

  1. PEP 3110 - Catching Exceptions in Python 3000

  2. PEP 344 - Exception Chaining and Embedded Tracebacks

关于Python 3 异常删除封闭范围内的变量,原因不明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29268892/

相关文章:

python - 与用户输入的数字比较总是产生 "not equal"结果

python - 大致近似Python中一串文本的宽度?

python - 如何在 Django 中使用 Gulp Browsersync?

python - 从 Python 源代码生成 UML

java - 异常线程 "main"java.lang.UnsatisfiedLinkError : org. lwjgl.DefaultSysImplementation.getPointerSize()I

java - 线程 "main"中出现 java.lang.noclassdeffounderror 异常

python - Scipy kstest 对于相似的值集返回不同的 p 值

delphi - Delphi:退出Delphi 6后的AV

python - Pandas 合并两个数据框,一个包含另一个数据框的列值

python-3.x - 训练多个 Keras NN 模型时出现段错误(核心转储)