为什么Python 2.7不允许我在收益后隐式重新引发异常?

joe*_*ker 7 python generator python-2.7

我在Python 2.7.5中发现了一个奇怪的行为except::

def generator():
    try:
        raise Exception()
    except:
        yield
        raise

list(generator())
Run Code Online (Sandbox Code Playgroud)

此代码失败 TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType

为什么Python会这样做而不是重新引发异常,就像yield之前没有那样raise

(显然Python 3修复了这个疣,函数会产生一个[None]列表,如你所料.)

(解决方法是异常存储在一个变量:except Exception as e: yield; raise e)

dan*_*ano 6

这只是Python 2.x中的一个错误.根据错误报告,问题在Python 3中已得到修复,但由于向后移植的复杂性,修复程序在进入维护模式之前从未达到2.7:

这在Python 3中已得到修复.我不知道是否值得向后移植更改,因为可能很难避免向异步模型中向后移植不兼容性.

八个月后......

2.7现在正在维护中,这不会被移植回来.