__exit __()(上下文管理器)中的exc_value参数是字符串而不是Exception(Python 2.6) [英] exc_value parameter from __exit__() (context manager) is string instead of Exception (Python 2.6)
问题描述
我试图弄乱上下文管理器,并在使用Python 2.6运行代码时感到有些惊讶。实际上, exc_value
参数似乎是一个字符串而不是一个异常。
I tried to mess around with context managers and got a bit surprised when running my code with Python 2.6. Indeed, the exc_value
parameter seems to be a string instead of an exception.
一些代码可以点亮这个问题:
A bit of code to hi-light this issue :
import sys
class contextmanager(object):
def __enter__(self):
pass
def __exit__(self, type_, value, traceback):
assert (type_ is None) == (value is None)
if value is not None:
print(type(value))
if __name__ == '__main__':
print(sys.version_info)
with contextmanager():
__name_ # should trigger name exception
Python 2.7:
With Python 2.7 :
<type 'exceptions.NameError'> # GOOD
Traceback (most recent call last):
File "test_conman.py", line 17, in <module>
__name_
NameError: name '__name_' is not defined
使用Python 3.2 :
With Python 3.2 :
sys.version_info(major=3, minor=2, micro=3, releaselevel='final', serial=0)
<class 'NameError'> # GOOD
Traceback (most recent call last):
File "test_conman.py", line 17, in <module>
__name_
NameError: name '__name_' is not defined
使用Python 2.6 :
With Python 2.6 :
(2, 6, 7, 'final', 0)
<type 'str'> # BAD
Traceback (most recent call last):
File "test_conman.py", line 17, in <module>
__name_
NameError: name '__name_' is not defined
我的理解是 exc_value
应该始终是一个例外。
我做错了什么吗?
有什么我误解了吗?
这是一个已知问题吗?
My understanding is that exc_value
should always be an exception.
Is there anything I did wrong ?
Is there anything I misunderstood ?
Is this a known issue ?
参考文献
Python 2文档: object .__ exit __(self,exc_type,exc_value,traceback)
推荐答案
错误,请参见问题7853 。它在Python 2.7a3中已修复,但从未向后移植到2.6分支。
This was a bug in Python 2.6, see issue 7853. It was fixed for Python 2.7a3 but never backported to the 2.6 branch.
换句话说,您没有做错任何事情,Python做了。
In other words, you did nothing wrong, Python did.
不幸的是,除了处理您在2.6中没有异常实例而是仅包含字符串值这一事实之外,没有其他解决方法。
Unfortunately, there's no real work-around other than to handle the fact that you don't have an exception instance in 2.6 but only the string value.
这篇关于__exit __()(上下文管理器)中的exc_value参数是字符串而不是Exception(Python 2.6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!