Is it possible to know if generator was used? i.e.
def code_reader(code):
for c in code:
yield c
code_rdr = code_reader(my_code)
a = code_rdr.next()
foo(code_rdr)
After foo
call I would like to know if .next()
was called on code_rdr
by foo
or not.
Of course I could wrap it by some class with a counter for next()
calls.
Is there any easy way to do so?
Python 3.2+ has inspect.getgeneratorstate()
. So you can simply use inspect.getgeneratorstate(gen) == 'GEN_CREATED'
:
>>> import inspect
>>> gen = (i for i in range(3))
>>> inspect.getgeneratorstate(gen)
'GEN_CREATED'
>>> next(gen)
0
>>> inspect.getgeneratorstate(gen)
'GEN_SUSPENDED'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With