且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有Python函数检查生成器是否已启动?

更新时间:2023-11-28 23:42:40

为避免向刚启动的生成器发送非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.