In order not to send a non- None value to the generator with start enabled, first call next or send(None) . I agree with the rest that David Beazley coroutine decorator (in python 3.x you need to call the __next__() function instead of next() ) is a great option. Although this decorator is simple, I have also successfully used the copipes library, which is a good implementation of many of the utilities from Beazley's presentation, including coroutines.
Regarding whether the generator can be checked to start - in Python 3 you can use inspect.getgeneratorstate . This is not available in Python 2, but the CPython implementation is pure python and does not rely on anything new for Python 3, so you can test 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
In particular, g2 starts if inspect.getgeneratorstate(g2) != inspect.GEN_CREATED .
Rich Frank Jul 18 '13 at 1:05 2013-07-18 01:05
source share