当该名称用于绑定捕获的异常时,如何阻止Python删除名称绑定?这种行为改变何时进入Python?
我正在编写代码以在Python 2和Python 3上运行:
exc = None
try:
1/0
text_template = "All fine!"
except ZeroDivisionError as exc:
text_template = "Got exception: {exc.__class__.__name__}"
print(text_template.format(exc=exc))
Run Code Online (Sandbox Code Playgroud)
请注意,在异常处理之前exc显式绑定,因此Python知道它是外部作用域中的名称.
在Python 2.7上,这运行正常,exc名称仍然可用于format调用::
Got exception: ZeroDivisionError
Run Code Online (Sandbox Code Playgroud)
太棒了,这正是我想要的:except子句绑定名称,我可以在函数的其余部分使用该名称来引用异常对象.
在Python 3.5上,format调用失败,因为显然删除了exc
绑定::
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NameError: name 'exc' is not defined
Run Code Online (Sandbox Code Playgroud)
为什么exc从外部范围删除绑定?我们如何在
条款之后可靠地保留名称绑定以使用它except?
这个变化何时进入Python,它在哪里记录?
我是否应该将此报告为Python 3中的错误?