如何检查是否使用了生成器?

How to check if generator was used?

是否可以知道是否使用了生成器?即

def code_reader(code):
   for c in code:
        yield c

code_rdr = code_reader(my_code)

a = code_rdr.next()

foo(code_rdr)

foo 调用后 我想知道 .next() 是否被 foocode_rdr 上调用。 当然,我可以用一些 class 和 next() 调用的计数器来包装它。 有什么简单的方法吗?

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'

我使用了附加的可能答案中的想法,重新定义了波纹管code_reader函数:

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

通过使用 .send('position') 我会知道要生成的下一个项目的位置,即

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')

输出:

0
0
f
1
1
o
2