Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if generator was used?

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?

like image 966
www Avatar asked Jan 04 '23 09:01

www


1 Answers

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'
like image 184
Chris_Rands Avatar answered Jan 16 '23 21:01

Chris_Rands