Python 如何在生成器中包装返回连续值的函数?

Python 如何在生成器中包装返回连续值的函数?,python,python-3.x,Python,Python 3.x,我有一个函数bar(obj),它从一个对象返回连续的值,直到它耗尽为止,在这一点上它返回False(忽略这不是Foo上的一个方法,或者我返回的是整数,这只是一个MVCE来演示某些东西的消耗)。我希望将该函数包装在生成器中,以便可以惰性地迭代这些值,但我显然缺少一些逻辑,因为这不起作用: class Foo: def __init__(self): self.counter = 0 def inc(self): if self.counter &l

我有一个函数
bar(obj)
,它从一个对象返回连续的值,直到它耗尽为止,在这一点上它返回
False
(忽略这不是
Foo
上的一个方法,或者我返回的是整数,这只是一个MVCE来演示某些东西的消耗)。我希望将该函数包装在生成器中,以便可以惰性地迭代这些值,但我显然缺少一些逻辑,因为这不起作用:

class Foo:
    def __init__(self):
        self.counter = 0

    def inc(self):
        if self.counter <= 9:
            self.counter += 1
            return self.counter
        else:
            return False


def bar(obj):
    return obj.inc()


def iterbar(obj):
    res = bar(obj)
    if res:
        yield res
    else:
        raise StopIteration

foo = Foo()
lazy = iterbar(foo)
next(lazy) # this yields 1, as expected
next(lazy) # this immediately raises StopIteration from somewhere other than iterbar
Foo类:
定义初始化(自):
self.counter=0
def公司(自我):

如果self.counter您没有循环以重复调用
bar
。第二次调用
next
后,它会选择
yield
停止的位置,到达函数的末尾,然后通过提升来指示

只需循环,然后
返回
停止:

def iterbar(obj):
    while True:
        res = bar(obj)
        if res:
            yield res
        else:
            return
或者,如果您想变得更花哨,并拥有Python 3.8+,您可以使用使其更简洁:

def iterbar(obj):
    while res := bar(obj):
        yield res

Foo
已经定义:
lazy=itertools.count()
。这太尴尬了。非常感谢。(将在约6分钟内接受)@urschrei Np。请注意,
StopIteration
是在从生成器函数返回时为您引发的,因此不需要显式的
raise StopIteration