是否有Python函数检查生成器是否已启动? [英] Is there a Python function that checks if a generator is started?

查看:68
本文介绍了是否有Python函数检查生成器是否已启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试定义一个生成器功能mycount(),可以用生成器功能send(0)重置该生成器功能,如下例所示.一切正常,除非当我在尚未启动的新生成器对象上使用send(0)时.在这种情况下,它给出一个TypeError.在这种情况下,是否有任何函数可以检查生成器是否已启动,还是必须捕获TypeError并使用mycount(0)创建新的生成器对象?

I try to define a generator function mycount() that can be reset with the generator function send(0) as in the example below. Everything works fine, except when I use send(0) on a new generator object that hasn't started yet. In this case it gives a TypeError. Is there any function that checks if the generator has started or do I have to catch the TypeError and create a new generator object with mycount(0) in such case?

def mycount(value):
    while True:
        v = yield value
        if v == None:
            value = value + 1
        else:
            value = v

g = mycount(3)
print(next(g))    # prints 3
print(next(g))    # prints 4
print(g.send(0))  # prints 0
print(next(g))    # prints 1
print(next(g))    # prints 2

g2 = mycount(3)
g2.send(0)
# TypeError: can't send non-None value to a just-started generator

推荐答案

为避免向刚启动的生成器发送非None值,您需要先调用nextsend(None).我同意其他人的观点,即大卫·比兹利(David Beazley)的协程装饰器(在python 3.x中,您需要调用__next__()函数而不是next())是一个不错的选择.尽管该特定装饰器很简单,但我还成功使用了 copipes 库,这是一个很好的库Beazley的演示文稿中许多实用程序的实现,包括协程.

To avoid sending a non-None value to a just-started generator, you need to call next or send(None) first. I agree with the others that David Beazley's coroutine decorator (in python 3.x you need to call to __next__() function instead of next()) is a great option. Though that particular decorator is simple, I've also successfully used the copipes library, which is a nice implementation of many of the utilities from Beazley's presentations, including coroutine.

关于是否可以检查生成器是否已启动-在Python 3中,您可以使用 inspect.getgeneratorstate .这在Python 2中不可用,但 CPython实现是纯python,不依赖于Python 3的任何新功能,因此您可以使用相同的方法进行检查:

Regarding whether one can check if a generator is started - in Python 3, you can use inspect.getgeneratorstate. This isn't available in Python 2, but the CPython implementation is pure python and doesn't rely on anything new to Python 3, so you can check yourself in the same way:

if generator.gi_running:
    return GEN_RUNNING
if generator.gi_frame is None:
    return GEN_CLOSED
if generator.gi_frame.f_lasti == -1:
    return GEN_CREATED
return GEN_SUSPENDED

具体来说,如果inspect.getgeneratorstate(g2) != inspect.GEN_CREATED,则启动g2.

Specifically, g2 is started if inspect.getgeneratorstate(g2) != inspect.GEN_CREATED.

这篇关于是否有Python函数检查生成器是否已启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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