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
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
.