www
www

Reputation: 4391

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?

Upvotes: 4

Views: 230

Answers (2)

www
www

Reputation: 4391

I have used idea from attached possible answers, bellow is redefined code_reader function:

def code_reader(code):
length = len(code)
i = 0
while i < length:
    val = (yield i)
    if val != 'position':
        yield code[i]
        i += 1

by using .send('position') on I would have know position of next item to be generated, i.e.

a = code_reader("foobar")

print a.next()
print a.send('position')
print a.next()
print a.send('position')
print a.send('position')
print a.next()
print a.send('position')

output:

0
0
f
1
1
o
2

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41168

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'

Upvotes: 10

Related Questions