GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — New coroutines chapter · python043/full-speed-python@256c687

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Makefile
  • chapters
    • coroutines.md
  • diagrams
    • consumers_pipeline.txt
    • coroutine_pipeline.txt
    • instructions.txt
  • images
    • consumers_pipeline.png
    • coroutine_pipeline.png
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Makefile‎

Copy file name to clipboardExpand all lines: Makefile
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ chapters = \
99
chapters/classes.md \
1010
chapters/iterators.md \
1111
chapters/generators.md \
12+
chapters/coroutines.md \
1213

1314
options = metadata.yaml --highlight-style tango
1415

Collapse file

‎chapters/coroutines.md‎

Copy file name to clipboard
+144Lines changed: 144 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Coroutines
2+
3+
Python coroutines are similar to generators but instead of producing data, coroutines are mostly used as data consumers. In other words, coroutines are functions that are resumed everytime a value is sent using the `send` method.
4+
5+
The trick with coroutines is the use of the `yield` keyword on the right side of an assignment expression. Here's an example of a coroutine that just prints the values that are sent to it:
6+
7+
```Python
8+
def coroutine():
9+
print('My coroutine')
10+
while True:
11+
val = yield
12+
print('Got', val)
13+
14+
>>> co = coroutine()
15+
>>> next(co)
16+
My coroutine
17+
>>> co.send(1)
18+
Got 1
19+
>>> co.send(2)
20+
Got 2
21+
>>> co.send(3)
22+
Got 3
23+
```
24+
25+
The initial call to `next` is required to move the coroutine forward. You can see that it executes the print statement. Eventually, the function reaches the `yield` expression where it will wait to be resumed. Then, everytime a value is sent (with `send`), the coroutine function resumes from the `yield`, copies the value to **val** and prints it.
26+
27+
Coroutines can be closed with the `close()` method.
28+
29+
```Python
30+
>>> co.close()
31+
>>> co.send(4)
32+
Traceback (most recent call last):
33+
File "<stdin>", line 1, in <module>
34+
StopIteration
35+
```
36+
37+
## Exercises with coroutines
38+
39+
1. Create a coroutine named "square" that prints the square of any sent value.
40+
41+
2. Implement the "minimize" coroutine that keeps and prints the minimum value that is sent to the function.
42+
43+
## Pipelines
44+
45+
Coroutines can be used to implement data pipelines where one coroutine will send data to the next coroutine in the pipeline. Coroutines push data into the pipeline using the `send()` method.
46+
47+
![](images/coroutine_pipeline.png)
48+
49+
Here's an example of a small pipeline where the values sent to the producer coroutine are squared and sent to the consumer coroutine for printing:
50+
51+
```Python
52+
def producer(consumer):
53+
print("Producer ready")
54+
while True:
55+
val = yield
56+
consumer.send(val * val)
57+
58+
def consumer():
59+
print("Consumer ready")
60+
while True:
61+
val = yield
62+
print('Consumer got', val)
63+
```
64+
65+
As above, coroutines must be "primed" with `next` before any value can be sent.
66+
67+
```Python
68+
>>> cons = consumer()
69+
>>> prod = producer(cons)
70+
>>> next(prod)
71+
Producer ready
72+
>>> next(cons)
73+
Consumer ready
74+
75+
>>> prod.send(1)
76+
Consumer got 1
77+
>>> prod.send(2)
78+
Consumer got 4
79+
>>> prod.send(3)
80+
Consumer got 9
81+
```
82+
83+
Also, with coroutines, data can be sent to multiple destinations.The following example implements two consumers where the first only prints numbers in 0..10 and the second only print numbers in 10..20:
84+
85+
```Python
86+
def producer(consumers):
87+
print("Producer ready")
88+
try:
89+
while True:
90+
val = yield
91+
for consumer in consumers:
92+
consumer.send(val * val)
93+
except GeneratorExit:
94+
for consumer in consumers:
95+
consumer.close()
96+
97+
def consumer(name, low, high):
98+
print("%s ready" % name)
99+
try:
100+
while True:
101+
val = yield
102+
if low < val < high:
103+
print('%s got' % name, val)
104+
except GeneratorExit:
105+
print("%s closed" % name)
106+
```
107+
108+
As before, coroutines must be "primed" before any value can be sent.
109+
110+
```Python
111+
>>> con1 = consumer('Consumer 1', 00, 10)
112+
>>> con2 = consumer('Consumer 2', 10, 20)
113+
>>> prod = producer([con1, con2])
114+
115+
>>> next(prod)
116+
Producer ready
117+
>>> next(con1)
118+
Consumer 1 ready
119+
>>> next(con2)
120+
Consumer 2 ready
121+
122+
>>> prod.send(1)
123+
Consumer 1 got 1
124+
>>> prod.send(2)
125+
Consumer 1 got 4
126+
>>> prod.send(3)
127+
Consumer 1 got 9
128+
>>> prod.send(4)
129+
Consumer 2 got 16
130+
131+
>>> prod.close()
132+
Consumer 1 closed
133+
Consumer 2 closed
134+
```
135+
136+
The data is sent to all consumers but only the second executes the print statement. Notice the use of the `GeneratorExit` exception. Sometimes it can be useful to catch the exception and inform the downstream coroutines that the pipeline is no longer useful.
137+
138+
![](images/consumers_pipeline.png)
139+
140+
## Exercises with coroutine pipelines
141+
142+
1. Implement a producer-consumer pipeline where the values squared by the producer are sent to two consumers. One should store and print the minimum value sent so far and the other the maximum value.
143+
144+
2. Implement a producer-consumer pipeline where the values squared by the producer are dispatched to two consumers, one at a time. The first value should be sent to consumer 1, the second value to consumer 2, third value to consumer 1 again, and so on. Closing the producer should force the consumers to print a list with the numbers that each one obtained.
Collapse file

‎diagrams/consumers_pipeline.txt‎

Copy file name to clipboard
+13Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
+-------------+
2+
send() | |
3+
+---->+ CONSUMER #1 |
4+
| | |
5+
+----------+ +----------+ | +-------------+
6+
| | send() | +--+
7+
| SOURCE +------->+ PRODUCER |
8+
| | | +--+
9+
+----------+ +----------+ | +-------------+
10+
| | |
11+
+---->+ CONSUMER #2 |
12+
send() | |
13+
+-------------+
Collapse file

‎diagrams/coroutine_pipeline.txt‎

Copy file name to clipboard
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
+----------+ +-----------+ +-----------+
2+
| | send() | | send() | |
3+
| SOURCE +------->+ COROUTINE +------->+ COROUTINE |
4+
| | | | | |
5+
+----------+ +-----------+ +-----------+
6+
7+
8+
9+
Collapse file

‎diagrams/instructions.txt‎

Copy file name to clipboard
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
1. Draw diagrams with http://asciiflow.com/
2+
2. Convert to png with http://ditaa.sourceforge.net/
3+
3. java -jar ditaa0_9.jar XXX.txt --scale 2
Collapse file

‎images/consumers_pipeline.png‎

Copy file name to clipboard
21.1 KB
  • Display the source diff
  • Display the rich diff
Loading
Collapse file

‎images/coroutine_pipeline.png‎

Copy file name to clipboard
7.52 KB
  • Display the source diff
  • Display the rich diff
Loading

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.