Python 3.3+inspectfunction
inspect.getgeneratorlocals()
coroutines and generators
A dict of the current local variables of a suspended generator, for peeking at its state in a test or debugger.
Syntax
inspect.getgeneratorlocals(generator)
Only variables already assigned by the current yield are visible: before the first next() it holds only the arguments, and after exhaustion or close() it is empty too because the frame is gone. It is a snapshot: editing the dict does not affect the generator. Anything that is not a generator (a list, say) raises TypeError.
Examples
import inspect
def counter():
total = 0
for i in range(3):
total += i
yield total
gen = counter()
print(inspect.getgeneratorlocals(gen)) # → {}
next(gen); next(gen)
print(inspect.getgeneratorlocals(gen)) # → {'total': 1, 'i': 1}
gen.close()
print(inspect.getgeneratorlocals(gen)) # → {}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy