@@ -109,50 +109,89 @@ To actually run a coroutine asyncio provides three main mechanisms:
109
109
Awaitables
110
110
==========
111
111
112
- We say that an object is an *awaitable * object if it can be used
113
- in an :keyword: `await ` expression.
112
+ We say that an object is an **awaitable ** object if it can be used
113
+ in an :keyword: `await ` expression. Many asyncio APIs are designed to
114
+ accept awaitables.
114
115
116
+ There are three main types of *awaitable * objects:
117
+ **coroutines **, **Tasks **, and **Futures **.
115
118
116
- .. rubric :: Coroutines and Tasks
117
119
118
- Python coroutines are *awaitables *::
120
+ .. rubric :: Coroutines
121
+
122
+ Python coroutines are *awaitables * and therefore can be awaited from
123
+ other coroutines::
124
+
125
+ import asyncio
119
126
120
127
async def nested():
121
128
return 42
122
129
123
130
async def main():
124
- # Will print "42":
125
- print(await nested())
131
+ # Nothing happens if we just call "nested()".
132
+ # (a coroutine object is created but not awaited)
133
+ nested()
134
+
135
+ # Let's do it differently now and await it:
136
+ print(await nested()) # will print "42".
137
+
138
+ asyncio.run(main())
139
+
140
+ .. important ::
141
+
142
+ In this documentation the term "coroutine" can be used for
143
+ two closely related concepts:
144
+
145
+ * a *coroutine function *: an :keyword: `async def ` function;
146
+
147
+ * a *coroutine object *: an object returned by calling a
148
+ *coroutine function *.
149
+
150
+ asyncio also supports legacy :ref: `generator-based
151
+ <asyncio_generator_based_coro>` coroutines.
152
+
153
+
154
+ .. rubric :: Tasks
126
155
127
156
*Tasks * are used to schedule coroutines *concurrently *.
128
- See the previous :ref: `section <coroutine >` for an introduction
129
- to coroutines and tasks.
130
157
131
- Note that in this documentation the term "coroutine" can be used for
132
- two closely related concepts:
158
+ When a coroutine is wrapped into a *Task * with functions like
159
+ :func: `asyncio.create_task ` the coroutine is automatically
160
+ scheduled to run soon::
161
+
162
+ import asyncio
163
+
164
+ async def nested():
165
+ return 42
133
166
134
- * a *coroutine function *: an :keyword: `async def ` function;
167
+ async def main():
168
+ # Schedule nested() to run soon concurrently
169
+ # with "main()".
170
+ task = asyncio.create_task(nested())
135
171
136
- * a *coroutine object *: object returned by calling a
137
- *coroutine function *.
172
+ # "task" can now be used to cancel "nested()", or
173
+ # can simply be awaited to wait until it is complete:
174
+ await task
175
+
176
+ asyncio.run(main())
138
177
139
178
140
179
.. rubric :: Futures
141
180
142
- There is a dedicated section about the :ref: `asyncio Future object
143
- <asyncio-futures>`, but the concept is fundamental to asyncio so
144
- it needs a brief introduction in this section.
181
+ A :class: `Future ` is a special **low-level ** awaitable object that
182
+ represents an **eventual result ** of an asynchronous operation.
183
+
184
+ When a Future object is *awaited * it means that the coroutine will
185
+ wait until the Future is resolved in some other place.
145
186
146
- A Future is a special **low-level ** awaitable object that represents
147
- an **eventual result ** of an asynchronous operation.
148
187
Future objects in asyncio are needed to allow callback-based code
149
188
to be used with async/await.
150
189
151
- Normally, **there is no need ** to create Future objects at the
190
+ Normally **there is no need ** to create Future objects at the
152
191
application level code.
153
192
154
193
Future objects, sometimes exposed by libraries and some asyncio
155
- APIs, should be awaited::
194
+ APIs, can be awaited::
156
195
157
196
async def main():
158
197
await function_that_returns_a_future_object()
@@ -163,6 +202,9 @@ APIs, should be awaited::
163
202
some_python_coroutine()
164
203
)
165
204
205
+ A good example of a low-level function that returns a Future object
206
+ is :meth: `loop.run_in_executor `.
207
+
166
208
167
209
Running an asyncio Program
168
210
==========================
@@ -192,8 +234,8 @@ Creating Tasks
192
234
193
235
.. function :: create_task(coro)
194
236
195
- Wrap the *coro * :ref: `coroutine <coroutine >` into a Task and
196
- schedule its execution. Return the Task object.
237
+ Wrap the *coro * :ref: `coroutine <coroutine >` into a :class: ` Task `
238
+ and schedule its execution. Return the Task object.
197
239
198
240
The task is executed in the loop returned by :func: `get_running_loop `,
199
241
:exc: `RuntimeError ` is raised if there is no running loop in
@@ -253,17 +295,17 @@ Sleeping
253
295
Running Tasks Concurrently
254
296
==========================
255
297
256
- .. awaitablefunction :: gather(\*fs , loop=None, return_exceptions=False)
298
+ .. awaitablefunction :: gather(\*aws , loop=None, return_exceptions=False)
257
299
258
- Run :ref: `awaitable objects <asyncio-awaitables >` in the *fs *
300
+ Run :ref: `awaitable objects <asyncio-awaitables >` in the *aws *
259
301
sequence *concurrently *.
260
302
261
- If any awaitable in *fs * is a coroutine, it is automatically
303
+ If any awaitable in *aws * is a coroutine, it is automatically
262
304
scheduled as a Task.
263
305
264
306
If all awaitables are completed successfully, the result is an
265
307
aggregate list of returned values. The order of result values
266
- corresponds to the order of awaitables in *fs *.
308
+ corresponds to the order of awaitables in *aws *.
267
309
268
310
If *return_exceptions * is ``True ``, exceptions are treated the
269
311
same as successful results, and aggregated in the result list.
@@ -273,7 +315,7 @@ Running Tasks Concurrently
273
315
If ``gather `` is *cancelled *, all submitted awaitables
274
316
(that have not completed yet) are also *cancelled *.
275
317
276
- If any Task or Future from the *fs * sequence is *cancelled *, it is
318
+ If any Task or Future from the *aws * sequence is *cancelled *, it is
277
319
treated as if it raised :exc: `CancelledError ` -- the ``gather() ``
278
320
call is **not ** cancelled in this case. This is to prevent the
279
321
cancellation of one submitted Task/Future to cause other
@@ -323,13 +365,13 @@ Running Tasks Concurrently
323
365
Shielding Tasks From Cancellation
324
366
=================================
325
367
326
- .. awaitablefunction :: shield(fut , \*, loop=None)
368
+ .. awaitablefunction :: shield(aw , \*, loop=None)
327
369
328
370
Protect an :ref: `awaitable object <asyncio-awaitables >`
329
371
from being :meth: `cancelled <Task.cancel> `.
330
372
331
- *fut * can be a coroutine, a Task, or a Future-like object. If
332
- *fut * is a coroutine it is automatically scheduled as a Task.
373
+ *aw * can be a coroutine, a Task, or a Future-like object. If
374
+ *aw * is a coroutine it is automatically scheduled as a Task.
333
375
334
376
The statement::
335
377
@@ -361,12 +403,12 @@ Shielding Tasks From Cancellation
361
403
Timeouts
362
404
========
363
405
364
- .. coroutinefunction :: wait_for(fut , timeout, \*, loop=None)
406
+ .. coroutinefunction :: wait_for(aw , timeout, \*, loop=None)
365
407
366
- Wait for the *fut * :ref: `awaitable <asyncio-awaitables >`
408
+ Wait for the *aw * :ref: `awaitable <asyncio-awaitables >`
367
409
to complete with a timeout.
368
410
369
- If *fut * is a coroutine it is automatically scheduled as a Task.
411
+ If *aw * is a coroutine it is automatically scheduled as a Task.
370
412
371
413
*timeout * can either be ``None `` or a float or int number of seconds
372
414
to wait for. If *timeout * is ``None ``, block until the future
@@ -381,7 +423,7 @@ Timeouts
381
423
The function will wait until the future is actually cancelled,
382
424
so the total wait time may exceed the *timeout *.
383
425
384
- If the wait is cancelled, the future *fut * is also cancelled.
426
+ If the wait is cancelled, the future *aw * is also cancelled.
385
427
386
428
The *loop * argument is deprecated and scheduled for removal
387
429
in Python 4.0.
@@ -409,22 +451,22 @@ Timeouts
409
451
# timeout!
410
452
411
453
.. versionchanged :: 3.7
412
- When *fut * is cancelled due to a timeout, ``wait_for `` waits
413
- for *fut * to be cancelled. Previously, it raised
454
+ When *aw * is cancelled due to a timeout, ``wait_for `` waits
455
+ for *aw * to be cancelled. Previously, it raised
414
456
:exc: `asyncio.TimeoutError ` immediately.
415
457
416
458
417
459
Waiting Primitives
418
460
==================
419
461
420
- .. coroutinefunction :: wait(fs , \*, loop=None, timeout=None,\
462
+ .. coroutinefunction :: wait(aws , \*, loop=None, timeout=None,\
421
463
return_when=ALL_COMPLETED)
422
464
423
- Run :ref: `awaitable objects <asyncio-awaitables >` in the *fs *
465
+ Run :ref: `awaitable objects <asyncio-awaitables >` in the *aws *
424
466
sequence concurrently and block until the condition specified
425
467
by *return_when *.
426
468
427
- If any awaitable in *fs * is a coroutine, it is automatically
469
+ If any awaitable in *aws * is a coroutine, it is automatically
428
470
scheduled as a Task.
429
471
430
472
Returns two sets of Tasks/Futures: ``(done, pending) ``.
@@ -465,12 +507,12 @@ Waiting Primitives
465
507
466
508
Usage::
467
509
468
- done, pending = await asyncio.wait(fs )
510
+ done, pending = await asyncio.wait(aws )
469
511
470
512
471
- .. function :: as_completed(fs , \*, loop=None, timeout=None)
513
+ .. function :: as_completed(aws , \*, loop=None, timeout=None)
472
514
473
- Run :ref: `awaitable objects <asyncio-awaitables >` in the *fs *
515
+ Run :ref: `awaitable objects <asyncio-awaitables >` in the *aws *
474
516
set concurrently. Return an iterator of :class: `Future ` objects.
475
517
Each Future object returned represents the earliest result
476
518
from the set of the remaining awaitables.
@@ -480,7 +522,7 @@ Waiting Primitives
480
522
481
523
Example::
482
524
483
- for f in as_completed(fs ):
525
+ for f in as_completed(aws ):
484
526
earliest_result = await f
485
527
# ...
486
528
@@ -670,6 +712,52 @@ Task Object
670
712
A Task is *done * when the wrapped coroutine either returned
671
713
a value, raised an exception, or the Task was cancelled.
672
714
715
+ .. method :: result()
716
+
717
+ Return the result of the Task.
718
+
719
+ If the Task is *done *, the result of the wrapped coroutine
720
+ is returned (or if the coroutine raised an exception, that
721
+ exception is re-raised.)
722
+
723
+ If the Task has been *cancelled *, this method raises
724
+ a :exc: `CancelledError ` exception.
725
+
726
+ If the Task's result isn't yet available, this method raises
727
+ a :exc: `InvalidStateError ` exception.
728
+
729
+ .. method :: exception()
730
+
731
+ Return the exception of the Task.
732
+
733
+ If the wrapped coroutine raised an exception that exception
734
+ is returned. If the wrapped coroutine returned normally
735
+ this method returns ``None ``.
736
+
737
+ If the Task has been *cancelled *, this method raises a
738
+ :exc: `CancelledError ` exception.
739
+
740
+ If the Task isn't *done * yet, this method raises an
741
+ :exc: `InvalidStateError ` exception.
742
+
743
+ .. method :: add_done_callback(callback, *, context=None)
744
+
745
+ Add a callback to be run when the Task is *done *.
746
+
747
+ This method should only be used in low-level callback-based code.
748
+
749
+ See the documentation of :meth: `Future.add_done_callback `
750
+ for more details.
751
+
752
+ .. method :: remove_done_callback(callback)
753
+
754
+ Remove *callback * from the callbacks list.
755
+
756
+ This method should only be used in low-level callback-based code.
757
+
758
+ See the documentation of :meth: `Future.remove_done_callback `
759
+ for more details.
760
+
673
761
.. method :: get_stack(\*, limit=None)
674
762
675
763
Return the list of stack frames for this Task.
0 commit comments