Python 3异常出现未知原因删除封闭作用域中的变量

18

我有以下代码:

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块之后插入了一个del e语句一样。这种行为是否有原因?如果Python开发人员希望except块具有自己的局部作用域,并且不会泄漏到周围作用域,我可以理解它,但为什么必须删除先前分配的外部作用域变量呢?
1个回答

23
引用 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 - 在Python 3000中捕获异常

  2. PEP 344 - 异常链接和嵌入式回溯


1
携带@Barry删除答案中的链接:https://www.wefearchange.org/2013/04/python-3-language-gotcha-and-short.html - Mr_and_Mrs_D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接