Generator Based Coroutines · Lecture 02 · 10 min

Generator States

A generator is always in one of four states (created, running, suspended or closed), and the inspect module can tell you which.

Python loads when you run a cell Shift+Enter runs a cell. Cells share variables, like a notebook.

Four states

To use generators as coroutines, you need a precise picture of what a generator object is doing at any moment. Start with a plain generator:

def gen(s):
    for c in s:
        yield c

g = gen('abc')
g

Calling gen('abc') did not run any of the body. It only built a generator object. At this point the generator is created: it has a frame ready to go, but it hasn’t executed a single line.

Calling next() starts it. The body runs until it hits a yield, hands the value to us, and is then suspended, frozen at that yield, waiting to be resumed:

print(next(g))
print(next(g))
print(next(g))

Each next() moves the generator from suspended back to running, until the next yield. When the body finally finishes (it returns, or falls off the end), next() raises StopIteration and the generator is closed for good:

try:
    next(g)
except StopIteration:
    print('StopIteration: the generator is exhausted')

So a generator moves through four states:

CREATED RUNNING SUSPENDED CLOSED next() yield next() / send() return / error close()
A generator only runs between a resume (next/send) and the next yield. It spends most of its life created, suspended or closed.

Asking a generator for its state

inspect.getgeneratorstate() reports the state as a string:

from inspect import getgeneratorstate

g = gen('abc')
print(getgeneratorstate(g))
next(g)
print(getgeneratorstate(g))
list(g)                       # consume the rest
print(getgeneratorstate(g))

You’ll see GEN_CREATED, GEN_SUSPENDED and GEN_CLOSED. What about GEN_RUNNING? From the outside you can never observe it: by the time next() returns to you, the generator has already suspended again. The only code that runs while a generator is running is the generator’s own body.

To catch it in the act, the body has to inspect itself. A generator doesn’t have a handy name for its own object, so we cheat and use a global variable:

def gen(s):
    for c in s:
        print('inside:', getgeneratorstate(global_gen))
        yield c

global_gen = gen('abc')
print(next(global_gen))
print('outside:', getgeneratorstate(global_gen))

The attributes behind the states

getgeneratorstate is a thin wrapper around attributes on the generator object:

def letters(s):
    for c in s:
        yield c

g = letters('xy')
print('frame:', g.gi_frame is not None, '| running:', g.gi_running, '| suspended:', g.gi_suspended)
next(g)
print('frame:', g.gi_frame is not None, '| running:', g.gi_running, '| suspended:', g.gi_suspended)
list(g)
print('frame:', g.gi_frame, '| running:', g.gi_running, '| suspended:', g.gi_suspended)
  • gi_frame is the generator’s execution frame (its local variables and the current position). It becomes None once the generator is closed, because there’s nothing left to resume.
  • gi_running is True only while the body is executing.
  • gi_suspended is True while it’s paused at a yield.
gi_suspended is new

gi_suspended was added in Python 3.11. On older versions, inspect worked out “suspended” by checking the frame’s instruction pointer. Either way, inspect.getgeneratorstate() is the portable way to ask, and it works the same on every Python 3 version.

Why a running generator can’t be resumed

Since a generator is either running or not, Python refuses to resume one that is already running. That can only happen if the body tries to advance itself:

def selfish():
    yield next(me)      # try to resume ourselves while running

me = selfish()
try:
    next(me)
except ValueError as ex:
    print('ValueError:', ex)

You’ll never write this on purpose, but it shows that “running” is a real, enforced state.

Why the states matter

For iteration, you rarely care: a for loop handles starting the generator and stopping on StopIteration for you. For coroutines, the state is everything:

  • You’ll send data only into a suspended generator. A created one hasn’t reached a yield yet, so there’s nowhere for the data to land.
  • You’ll close a generator to move it to the closed state on purpose, before it’s exhausted.
  • You’ll inspect states to understand what yield from does to a delegator and its subgenerator.

Key takeaways

  • A generator is created (not started), running (executing its body), suspended (paused at a yield) or closed (finished, or closed on purpose).
  • next() moves it from created or suspended to running; yield suspends it; returning or an uncaught exception closes it.
  • inspect.getgeneratorstate() returns GEN_CREATED, GEN_RUNNING, GEN_SUSPENDED or GEN_CLOSED. You can only see GEN_RUNNING from inside the body.
  • The same information lives in gi_frame, gi_running and (since 3.11) gi_suspended.