python - 为什么 Python 2.7 不允许我在 yield 之后隐式地重新引发异常?

标签 python python-2.7 generator

当在 except: block 中屈服时,我注意到 Python 2.7.5 中有一些奇怪的行为:

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

list(generator())

此代码因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)

最佳答案

这只是 Python 2.x 中的一个错误。根据bug report ,该问题已在 Python 3 中修复,但由于向后移植它的复杂性,该修复在进入维护模式之前从未在 2.7 中实现:

This is fixed in Python 3. I don't know if it's worth backporting the changes because it may be hard to avoid also backporting the incompatibilities in the exception model.

八个月后...

This won't get backported now that 2.7 is in maintenance.

关于python - 为什么 Python 2.7 不允许我在 yield 之后隐式地重新引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189545/

相关文章:

python - OpenCV 错误:错误:(-215)scn == 3 ||函数 cv::cvtColor 中的 scn == 4

python - 类中的生成器表达式未产生我期望的输出

javascript - 为什么在此示例中使用生成器函数比填充和迭代数组慢?

调用时刷新缓冲区的 Python 打印函数?

python - 迭代算法到递归的转换

python - 使用Python加载数据到Mysql

python - 从字符串中拆分并删除整行

python - 从上下文管理器中取出生成器

python - 如何在Python中复制或删除有条件的行

python - 如何在 Python + Selenium 中获取元素的值