如何立即运行生成器函数的初始化代码,而不是在第一次调用时?

Rya*_*son 12 python eager generator multiprocessing

我有一个生成器函数,如下所示:

def mygenerator():
    next_value = compute_first_value() # Costly operation
    while next_value != terminating_value:
        yield next_value
        next_value = compute_next_value()
Run Code Online (Sandbox Code Playgroud)

我希望初始化步骤(在while循环之前)在调用函数时立即运行,而不是仅在首次使用生成器时运行.有什么好办法呢?

我想这样做,因为生成器将在一个单独的线程(或进程,或任何多处理使用)中运行,我将不会在短时间内使用返回,并且初始化有点昂贵,所以我希望它我正准备使用这些值时进行初始化.

And*_*oev 14

class mygenerator(object):
    def __init__(self):
        next_value = compute_first_value()
    def __iter__(self):
        return self
    def next(self):
        if next_value == terminating_value:
            raise StopIteration()
        return next_value
Run Code Online (Sandbox Code Playgroud)


Jas*_*n A 10

我需要类似的东西.这就是我的目标.将发电机功能推入内部并返回其呼叫.

def mygenerator():
    next_value = compute_first_value()

    def generator():
        while next_value != terminating_value:
            yield next_value
            next_value = compute_next(next_value)

    return generator()
Run Code Online (Sandbox Code Playgroud)


nco*_*lan 8

您可以使用itertools.chain以下方法轻松创建"预制"迭代器:

from itertools import chain

def primed(iterable):
    """Preprimes an iterator so the first value is calculated immediately
       but not returned until the first iteration
    """
    itr = iter(iterable)
    try:
        first = next(itr)  # itr.next() in Python 2
    except StopIteration:
        return itr
    return chain([first], itr)

>>> def g():
...     for i in range(5):
...         print("Next called")
...         yield i
...
>>> x = primed(g())
Next called
>>> for i in x: print(i)
...
0
Next called
1
Next called
2
Next called
3
Next called
4
Run Code Online (Sandbox Code Playgroud)


Ste*_*ard 5

我想你可以在第一个语句完成之后,然后在你的调用代码中产生None:

gen = mygenerator()
next(gen) # toss the None
do_something(gen)
Run Code Online (Sandbox Code Playgroud)