How to check if a generator was used?

Can I find out if a 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 the call foo, I would like to know whether the call was .next()on code_rdrto fooor not. Of course, I could wrap it in some class using a call counter next(). Is there an easy way to do this?

+4
source share
2 answers

I used the idea from the attached possible answers, the redefined code_readerfunction is described below :

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

using .send ('position'), I would know the position of the next element 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
0
source

Python 3.2+ inspect.getgeneratorstate(). 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'
+9

Source: https://habr.com/ru/post/1671980/


All Articles