gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:46:20 24 4
gpt4 key购买 nike

当在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com