Is there a Python function that checks if a generator is started?

前端 未结 4 430
轻奢々
轻奢々 2021-01-05 00:46

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 01:16

    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.

    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
    

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

提交回复
热议问题