gpt4 book ai didi

python - Python 生成器可以非延迟调用吗?

转载 作者:行者123 更新时间:2023-12-01 01:25:57 24 4
gpt4 key购买 nike

我知道在Python中,生成器是延迟调用的。例如:

>>> def G():
... print('this was evaluated now 1')
... yield 1
... print('this was evaluated now 2')
... yield 2
...
>>> g = G()
>>> next(g)
this was evaluated now 1
1
>>> next(g)
this was evaluated now 2
2

仅在调用第一个 next(g) 后才对 print('this wasvalued now 1') 行进行求值。

我想知道是否有一种简单的方法来非延迟地调用生成器。这意味着当调用 g = G() 时,该函数将计算直到并包括第一个 yield 结果的所有内容,而不实际产生。然后,在第一次调用 next(g) 时,将产生已经计算的结果,并且还将计算直到并包括第二个 yield 结果的所有内容。等等。

如何实现这一目标?

<小时/>

以下是此非惰性方案下的预期行为:

>>> g = G()
this was evaluated now 1
>>> next(g)
1
this was evaluated now 2
>>> next(g)
2
<小时/>

这是一个解决方案尝试,但不起作用:

>>> class NonLazyGenerator():
... def __init__(self,G):
... self.g = G()
... self.next_value = next(self.g)
...
... def __next__(self):
... current_value = self.next_value
... try:
... self.next_value = next(self.g)
... except StopIteration:
... pass
... return current_value
...
>>> g = NonLazyGenerator(G)
this was evaluated now 1
>>> next(g)
this was evaluated now 2
1
>>> next(g)
2

这会失败,因为该值仅在 return 语句之后生成,而直到下一个 yield 的所有计算都发生在 return 之前> 声明。这个例子让我意识到,可能无法执行我正在寻找的东西,因为它需要在函数返回后执行步骤(可能需要多线程)。

最佳答案

您可能可以为其编写某种装饰器,例如:

def eagergenerator(mygen):
class GeneratorWrapper:
def __init__(self, *args, **kwargs):
self.g = mygen(*args, **kwargs)
self.last = next(self.g)
def __iter__(self):
return self
def __next__(self):
if self.last is self:
raise StopIteration
fake_yield = self.last
try:
self.last = next(self.g)
return fake_yield
except StopIteration:
self.last = self
return fake_yield
return GeneratorWrapper

然后你可以简单地装饰你的普通发电机:

@eagergenerator
def G():
print("one")
yield 1
print("two")
yield 2

其工作原理如下:

>>> g = G()                               
one
>>> next(g)
two
1
>>> next(g)
2
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "eagergen.py", line 10, in __next__
raise StopIteration
StopIteration
>>>

关于python - Python 生成器可以非延迟调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333470/

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