如何立即而不是在第一次调用时运行生成器函数的初始化代码? [英] How can I run the initialization code for a generator function immediately, rather than at the first call?

查看:88
本文介绍了如何立即而不是在第一次调用时运行生成器函数的初始化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成器函数,其内容如下:

I have a generator function that goes something like this:

def mygenerator():
    next_value = compute_first_value() # Costly operation
    while next_value != terminating_value:
        yield next_value
        next_value = compute_next_value()

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

I would like the initialization step (before the while loop) to run as soon as the function is called, rather than only when the generator is first used. What is a good way to do this?

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

I want to do this because the generator will be running in a separate thread (or process, or whatever multiprocessing uses) and I won't be using the return for a short while, and the initialization is somewhat costly, so I would like it to do the initialization while I'm getting ready to use the values.

推荐答案

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

这篇关于如何立即而不是在第一次调用时运行生成器函数的初始化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆