引发异常而不关闭python中的生成器

问题描述 投票:1回答:3

是否有可能从生成器引发异常(仅传递给.send()调用者),但没有在Python中关闭生成器?

考虑此代码:

def square_plus():
     n = 0
     i = 0
     while True:
         n = yield i + n**2
         i += 1

sp = square_plus()  # create generator
next(sp)            # prime it
print(sp.send(5))   # send 5 and expect 5*5+1
print(sp.send(3))   # send 3 and expect 3*3+2
print(sp.send("boom"))   # send rubbish and expect TypeError without destroying sp
print(sp.send(7))   # send 3 and expect 7*7+3

例如,我可以将这种特定的逻辑实现为闭包,但这不是重点。这只是保持简单的示例。我希望它成为发电机。感谢您的任何想法/提示。

python exception generator
3个回答
2
投票

不。生成器不支持该功能。您当然可以将生成器包装在某种类似于生成器接口的对象中,并且如果有人发布答案可以做到这一点,我也不会感到惊讶,但是actual generator不能从send引发异常或__next__不终止。


2
投票

[您能做的最好的就是捕获异常并返回一些标记值,例如None,并让生成器的用户通过检测此标记并重新发送一个值来进行协作。

def square_plus():
    n = 0
    i = 0
    while True:
        n = yield i + n**2
        while True:
            try:
                n = int(n)
            except ValueError:
                n = yield None
            else:
                i += 1
                break

sp = square_plus()  # create generator
next(sp)            # prime it
n = sp.send(5)
if n is not None:
    print(n)
n = sp.send(3)
if n is not None:
    print(n)
n = sp.send("boom")
if n is not None:  # n will be None, so nothing is printed here
    print(n)
n = sp.send(7)
if n is not None:
    print(n)

0
投票

我正在考虑产生一个值或一个异常对象,并用一个函数包装生成器,如果生成器中的值是异常,则该函数将引发异常,否则返回一个值。

© www.soinside.com 2019 - 2024. All rights reserved.