October 2018
Intermediate to advanced
420 pages
10h 26m
English
So how can generators help with writing asynchronous code? The twist comes from the fact that a generator can be interrupted where we want it to be and resumed later when something happens, such as when an asynchronous action is completed. This means that generators can be used to trigger asynchronous action executions with the yield expression, and they can be resumed when the action has completed.
Let's rewrite the state machine as a generator. The asynchronous operations are the read calls on the transport channel. So, each time the state machine needs to get some data, it has to yield so that more data can be read. Here is the new code of the state machine:
def parser(read_next): while True: ...