Skip to content

Commit 3978837

Browse files
committed
Add section describing coroutines roots in generators.
1 parent ebfe542 commit 3978837

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Doc/howto/a-conceptual-overview-of-asyncio.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,42 @@ Notably, the coroutine can be paused and resumed at various points within the
115115
function's body.
116116
That pausing and resuming ability is what allows for asynchronous behavior!
117117

118+
Coroutines and coroutine functions are built on top of generators and
119+
generator functions.
120+
Recall, a generator function is a function that ``yield``\s, like this one::
121+
122+
def get_random_number():
123+
# This would be a bad random number generator!
124+
print("Hi")
125+
yield 1
126+
print("Hello")
127+
yield 7
128+
print("Howdy")
129+
yield 4
130+
...
131+
132+
Like, a coroutine function, invoking a generator function does not run it.
133+
Instead, it provides a generator object::
134+
135+
>>> get_random_number()
136+
<generator object get_random_number at 0x1048671c0>
137+
>>>
138+
139+
You can "invoke" or proceed to the next ``yield`` of a generator by using the
140+
built-in function :func:`next`.
141+
In other words, the generator runs, then pauses.
142+
For example::
143+
144+
>>> generator = get_random_number()
145+
>>> next(generator)
146+
Hi
147+
1
148+
>>> next(generator)
149+
Hello
150+
7
151+
152+
153+
118154
=====
119155
Tasks
120156
=====

0 commit comments

Comments
 (0)