Effective Python Item 40: Consider Coroutines to Run Many Functions Concurrently
Threads give Python programmers a way to run multiple functions seemingly at the same time (see Item 37: “Use Threads for Blocking I/O, Avoid for Parallelism”). But there are three big problems with threads:
- They require special tools to coordinate with each other safely (see Item 38: “Use Lock to Prevent Data Races in Threads” and Item 39: “Use Queue to Coordinate Work Between Threads”). This makes code that uses threads harder to reason about than procedural, single-threaded code. This complexity makes threaded code more difficult to extend and maintain over time.
- Threads require a lot of memory, about 8 MB per executing thread. On many computers, that amount of memory doesn’t matter for a dozen threads or so. But what if you want your program to run tens of thousands of functions “simultaneously”? These functions may correspond to user requests to a server, pixels on a screen, particles in a simulation, etc. Running a thread per unique activity just won’t work.
- Threads are costly to start. If you want to constantly be creating new concurrent functions and finishing them, the overhead of using threads becomes large and slows everything down.
Python can work around all these issues with coroutines. Coroutines let you have many seemingly simultaneous functions in your Python programs. They’re implemented as an extension to generators. The cost of starting a generator coroutine is a function call. Once active, they each use less than 1 KB of memory until they’re exhausted.
Coroutines work by enabling the code consuming a generator to send a value back into the generator function after each yield expression. The generator function receives the value passed to the send function as the result of the corresponding yield expression.
while True: received
'Received:', received) it
# Prime the coroutineit.send(
'Second') >>> Received: First Received: Second
The initial call to next is required to prepare the generator for receiving the first send by advancing it to the first yield expression. Together, yield and send provide generators with a standard way to vary their next yielded value in response to external input.
For example, say you want to implement a generator coroutine that yields the minimum value it’s been sent so far. Here, the bare yield prepares the coroutine with the initial minimum value sent in from the outside. Then the generator repeatedly yields the new minimum in exchange for the next value to consider.
while True: value
The code consuming the generator can run one step at a time and will output the minimum value seen after each input.
# Prime the generator
1)) >>> 10 4 4 -1
The generator function will seemingly run forever, making forward progress with each new call to send. Like threads, coroutines are independent functions that can consume inputs from their environment and produce resulting outputs. The difference is that coroutines pause at each yield expression in the generator function and resume after each call to send from the outside. This is the magical mechanism of coroutines.
This behavior allows the code consuming the generator to take action after each yield expression in the coroutine. The consuming code can use the generator’s output values to call other functions and update data structures. Most importantly, it can advance other generator functions until their next yield expressions. By advancing many separate generators in lockstep, they will all seem to be running simultaneously, mimicking the concurrent behavior of Python threads.
The Game of Life
Let me demonstrate the simultaneous behavior of coroutines with an example. Say you want to use coroutines to implement Conway’s Game of Life. The rules of the game are simple. You have a two-dimensional grid of an arbitrary size. Each cell in the grid can either be alive or empty.
The game progresses one tick of the clock at a time. At each tick, each cell counts how many of its neighboring eight cells are still alive. Based on its neighbor count, each cell decides if it will keep living, die, or regenerate. Here’s an example of a 5×5 Game of Life grid after four generations with time going to the right. I’ll explain the specific rules further below.
0 | 1 | 2 | 3 | 4 ----- | ----- | ----- | ----- | ----- -*--- | --*-- | --**- | --*-- | ----- --**- | --**- | -*--- | -*--- | -**-- ---*- | --**- | --**- | --*-- | ----- ----- | ----- | ----- | ----- | -----
I can model this game by representing each cell as a generator coroutine running in lockstep with all the others.
To implement this, first I need a way to retrieve the status of neighboring cells. I can do this with a coroutine named count_neighbors that works by yielding Query objects. The Query class I define myself. Its purpose is to provide the generator coroutine with a way to ask its surrounding environment for information.
The coroutine yields a Query for each neighbor. The result of each yield expression will be the value ALIVE or EMPTY. That’s the interface contract I’ve defined between the coroutine and its consuming code. The count_neighbors generator sees the neighbors’ states and returns the count of living neighbors.
defcount_neighbors(y, x): n_
# Define e_, se, s_, sw, w_, nw ...
=[n_, ne, e_, se, s_, sw, w_, nw]
inneighbor_states: if state
I can drive the count_neighbors coroutine with fake data to test it. Here, I show how Query objects will be yielded for each neighbor. count_neighbors expects to receive cell states corresponding to each Query through the coroutine’s send method. The final count is returned in the StopIteration exception that is raised when the generator is exhausted by the return statement.
# Get the first query
'First yield: ', q1) q2
# Send q1 state, get q2
'Second yield:', q2) q3
# Send q2 state, get q3
# ...try: count
# Send q8 state, retrieve count
'Count: ', e.value)
# Value from return statement>>> First yield: Query(y=11, x=5) Second yield: Query(y=11, x=6) ... Count: 2
Now I need the ability to indicate that a cell will transition to a new state in response to the neighbor count that it found from count_neighbors. To do this, I define another coroutine called step_cell. This generator will indicate transitions in a cell’s state by yielding Transition objects. This is another class that I define, just like the Query class.
The step_cell coroutine receives its coordinates in the grid as arguments. It yields a Query to get the initial state of those coordinates. It runs count_neighbors to inspect the cells around it. It runs the game logic to determine what state the cell should have for the next clock tick. Finally, it yields a Transition object to tell the environment the cell’s next state.
defstep_cell(y, x): state
yieldQuery(y, x) neighbors
yield fromcount_neighbors(y, x) next_state
yieldTransition(y, x, next_state)
Importantly, the call to count_neighbors uses the yield from expression. This expression allows Python to compose generator coroutines together, making it easy to reuse smaller pieces of functionality and build complex coroutines from simpler ones. When count_neighbors is exhausted, the final value it returns (with the return statement) will be passed to step_cell as the result of the yield from expression.
Now, I can finally define the simple game logic for Conway’s Game of Life. There are only three rules.
defgame_logic(state, neighbors): if state
==ALIVE: if neighbors
<2: return EMPTY
# Die: Too fewelif neighbors
>3: return EMPTY
# Die: Too manyelse: if neighbors
==3: return ALIVE
# Regeneratereturn state
I can drive the step_cell coroutine with fake data to test it.
# Initial location query
'Me: ', q0) q1
# Send my status, get neighbor query
'Q1: ', q1)
# Send for q8, get game decision
'Outcome: ', t1) >>> Me: Query(y=10, x=5) Q1: Query(y=11, x=5) ... Outcome: Transition(y=10, x=5, state='-')
The goal of the game is to run this logic for a whole grid of cells in lockstep. To do this, I can further compose the step_cell coroutine into a simulate coroutine. This coroutine progresses the grid of cells forward by yielding from step_cell many times. After progressing every coordinate, it yields a TICK object to indicate that the current generation of cells have all transitioned.
range(height): for x in
yield fromstep_cell(y, x)
What’s impressive about simulate is that it’s completely disconnected from the surrounding environment. I still haven’t defined how the grid is represented in Python objects, how Query, Transition, and TICK values are handled on the outside, nor how the game gets its initial state. But the logic is clear. Each cell will transition by running step_cell. Then the game clock will tick. This will continue forever, as long as the simulate coroutine is advanced.
This is the beauty of coroutines. They help you focus on the logic of what you’re trying to accomplish. They decouple your code’s instructions for the environment from the implementation that carries out your wishes. This enables you to run coroutines seemingly in parallel. This also allows you to improve the implementation of following those instructions over time without changing the coroutines.
Now, I want to run simulate in a real environment. To do that, I need to represent the state of each cell in the grid. Here, I define a class to contain the grid:
def__init__(self, height, width): self.height
The grid allows you to get and set the value of any coordinate. Coordinates that are out of bounds will wrap around, making the grid act like infinite looping space.
defquery(self, y, x):
defassign(self, y, x, state): self.rows[y
At last, I can define the function that interprets the values yielded from simulate and all of its interior coroutines. This function turns the instructions from the coroutines into interactions with the surrounding environment. It progresses the whole grid of cells forward a single step and then returns a new grid containing the next state.
deflive_a_generation(grid, sim): progeny
=Grid(grid.height, grid.width) item
isinstance(item, Query): state
=grid.query(item.y, item.x) item
# Must be a Transitionprogeny.assign(item.y, item.x, item.state) item
To see this function in action, I need to create a grid and set its initial state. Here, I make a classic shape called a glider.
Now I can progress this grid forward one generation at a time. You can see how the glider moves down and to the right on the grid based on the simple rules from the game_logic function.
The best part about this approach is that I can change the game_logic function without having to update the code that surrounds it. I can change the rules or add larger spheres of influence with the existing mechanics of Query, Transition, and TICK. This demonstrates how coroutines enable the separation of concerns, which is an important design principle.
Coroutines in Python 2
Unfortunately, Python 2 is missing some of the syntactical sugar that makes coroutines so elegant in Python 3. There are two limitations. First, there is no yield from expression. That means that when you want to compose generator coroutines in Python 2, you need to include an additional loop at the delegation point.
# Python 2
# yield from in Python 3yield value
print list(composed()) >>> ['A', 1, 2, 'B']
The second limitation is that there is no support for the return statement in Python 2 generators. To get the same behavior that interacts correctly with try/except/finally blocks, you need to define your own exception type and raise it when you want to return a value.
# Python 2
def__init__(self, value): self.value
# return 2 in Python 3
print list(composed()) >>> [1, 8]
Things to Remember
- Coroutines provide an efficient way to run tens of thousands of functions seemingly at the same time.
- Within a generator, the value of the yield expression will be whatever value was passed to the generator’s send method from the exterior code.
- Coroutines give you a powerful tool for separating the core logic of your program from its interaction with the surrounding environment.
- Python 2 doesn’t support yield from or returning values from generators.