blob: 7fbfd426dba6c533c742e7e50defdc86de76e442 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov512d7102018-09-17 19:35:30 -04003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov512d7102018-09-17 19:35:30 -04008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov512d7102018-09-17 19:35:30 -040011.. contents::
12 :depth: 1
13 :local:
14
lf627d2c82017-07-25 17:03:51 -060015
Victor Stinnerea3183f2013-12-03 01:08:00 +010016.. _coroutine:
17
18Coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov512d7102018-09-17 19:35:30 -040021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Miss Islington (bot)45452b72018-09-18 00:00:58 -070023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov512d7102018-09-17 19:35:30 -040026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov512d7102018-09-17 19:35:30 -040028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov512d7102018-09-17 19:35:30 -040033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov512d7102018-09-17 19:35:30 -040037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov512d7102018-09-17 19:35:30 -040040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov512d7102018-09-17 19:35:30 -040043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Yury Selivanov512d7102018-09-17 19:35:30 -040045* The :func:`asyncio.run` function to run the top-level
46 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Yury Selivanov512d7102018-09-17 19:35:30 -040048* Awaiting on a coroutine. The following snippet of code will
49 print "hello" after waiting for 1 second, and then print "world"
50 after waiting for *another* 2 seconds::
Victor Stinnerea3183f2013-12-03 01:08:00 +010051
Yury Selivanov512d7102018-09-17 19:35:30 -040052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov512d7102018-09-17 19:35:30 -040055 async def say_after(delay, what):
56 await asyncio.sleep(delay)
57 print(what)
58
59 async def main():
60 print('started at', time.strftime('%X'))
61
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
65 print('finished at', time.strftime('%X'))
66
67 asyncio.run(main())
68
69 Expected output::
70
71 started at 17:13:52
72 hello
73 world
74 finished at 17:13:55
75
76* The :func:`asyncio.create_task` function to run coroutines
77 concurrently as asyncio :class:`Tasks <Task>`.
78
Miss Islington (bot)9a89fd62018-09-17 23:27:07 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040080 *concurrently*::
81
82 async def main():
83 task1 = asyncio.create_task(
84 say_after(1, 'hello'))
85
86 task2 = asyncio.create_task(
87 say_after(2, 'world'))
88
89 print('started at', time.strftime('%X'))
90
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
96 print('finished at', time.strftime('%X'))
97
98 Note that expected output now shows that the snippet runs
99 1 second faster than before::
100
101 started at 17:14:32
102 hello
103 world
104 finished at 17:14:34
105
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700112We say that an object is an **awaitable** object if it can be used
113in an :keyword:`await` expression. Many asyncio APIs are designed to
114accept awaitables.
115
116There are three main types of *awaitable* objects:
117**coroutines**, **Tasks**, and **Futures**.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700118
119
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700120.. rubric:: Coroutines
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700121
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700122Python coroutines are *awaitables* and therefore can be awaited from
123other coroutines::
124
125 import asyncio
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700126
127 async def nested():
128 return 42
129
130 async def main():
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700131 # Nothing happens if we just call "nested()".
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700132 # A coroutine object is created but not awaited,
133 # so it *won't run at all*.
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700134 nested()
135
136 # Let's do it differently now and await it:
137 print(await nested()) # will print "42".
138
139 asyncio.run(main())
140
141.. important::
142
143 In this documentation the term "coroutine" can be used for
144 two closely related concepts:
145
146 * a *coroutine function*: an :keyword:`async def` function;
147
148 * a *coroutine object*: an object returned by calling a
149 *coroutine function*.
150
151asyncio also supports legacy :ref:`generator-based
152<asyncio_generator_based_coro>` coroutines.
153
154
155.. rubric:: Tasks
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700156
157*Tasks* are used to schedule coroutines *concurrently*.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700158
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700159When a coroutine is wrapped into a *Task* with functions like
160:func:`asyncio.create_task` the coroutine is automatically
161scheduled to run soon::
Yury Selivanov512d7102018-09-17 19:35:30 -0400162
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700163 import asyncio
Yury Selivanov512d7102018-09-17 19:35:30 -0400164
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700165 async def nested():
166 return 42
167
168 async def main():
169 # Schedule nested() to run soon concurrently
170 # with "main()".
171 task = asyncio.create_task(nested())
172
173 # "task" can now be used to cancel "nested()", or
174 # can simply be awaited to wait until it is complete:
175 await task
176
177 asyncio.run(main())
Victor Stinner337e03f2014-08-11 01:11:13 +0200178
Victor Stinnerea3183f2013-12-03 01:08:00 +0100179
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700180.. rubric:: Futures
181
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700182A :class:`Future` is a special **low-level** awaitable object that
183represents an **eventual result** of an asynchronous operation.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700184
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700185When a Future object is *awaited* it means that the coroutine will
186wait until the Future is resolved in some other place.
187
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700188Future objects in asyncio are needed to allow callback-based code
189to be used with async/await.
190
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700191Normally **there is no need** to create Future objects at the
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700192application level code.
193
194Future objects, sometimes exposed by libraries and some asyncio
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700195APIs, can be awaited::
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700196
197 async def main():
198 await function_that_returns_a_future_object()
199
200 # this is also valid:
201 await asyncio.gather(
202 function_that_returns_a_future_object(),
203 some_python_coroutine()
204 )
205
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700206A good example of a low-level function that returns a Future object
207is :meth:`loop.run_in_executor`.
208
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700209
Yury Selivanov512d7102018-09-17 19:35:30 -0400210Running an asyncio Program
211==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100212
Elvis Pranskevichus15f3d0c2018-05-19 23:39:45 -0400213.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500214
215 This function runs the passed coroutine, taking care of
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700216 managing the asyncio event loop and *finalizing asynchronous
217 generators*.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500218
219 This function cannot be called when another asyncio event loop is
220 running in the same thread.
221
Yury Selivanov512d7102018-09-17 19:35:30 -0400222 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500223
224 This function always creates a new event loop and closes it at
225 the end. It should be used as a main entry point for asyncio
226 programs, and should ideally only be called once.
227
228 .. versionadded:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400229 **Important:** this function has been added to asyncio in
230 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500231
232
Yury Selivanov512d7102018-09-17 19:35:30 -0400233Creating Tasks
234==============
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100235
Yury Selivanov512d7102018-09-17 19:35:30 -0400236.. function:: create_task(coro)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100237
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700238 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
239 and schedule its execution. Return the Task object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100240
Yury Selivanov512d7102018-09-17 19:35:30 -0400241 The task is executed in the loop returned by :func:`get_running_loop`,
242 :exc:`RuntimeError` is raised if there is no running loop in
243 current thread.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100244
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700245 This function has been **added in Python 3.7**. Prior to
246 Python 3.7, the low-level :func:`asyncio.ensure_future` function
247 can be used instead::
248
249 async def coro():
250 ...
251
252 # In Python 3.7+
253 task = asyncio.create_task(coro())
254 ...
255
256 # This works in all Python versions but is less readable
257 task = asyncio.ensure_future(coro())
258 ...
259
Yury Selivanov512d7102018-09-17 19:35:30 -0400260 .. versionadded:: 3.7
Victor Stinner7f314ed2014-10-15 18:49:16 +0200261
262
Yury Selivanov512d7102018-09-17 19:35:30 -0400263Sleeping
264========
Victor Stinner7f314ed2014-10-15 18:49:16 +0200265
Yury Selivanov512d7102018-09-17 19:35:30 -0400266.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinner7f314ed2014-10-15 18:49:16 +0200267
Yury Selivanov512d7102018-09-17 19:35:30 -0400268 Block for *delay* seconds.
269
270 If *result* is provided, it is returned to the caller
271 when the coroutine completes.
272
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700273 The *loop* argument is deprecated and scheduled for removal
274 in Python 4.0.
275
Yury Selivanov512d7102018-09-17 19:35:30 -0400276 .. _asyncio_example_sleep:
277
278 Example of coroutine displaying the current date every second
279 for 5 seconds::
Victor Stinner7f314ed2014-10-15 18:49:16 +0200280
281 import asyncio
282 import datetime
283
Yury Selivanov02a0a192017-12-14 09:42:21 -0500284 async def display_date():
285 loop = asyncio.get_running_loop()
Yury Selivanov66f88282015-06-24 11:04:15 -0400286 end_time = loop.time() + 5.0
287 while True:
288 print(datetime.datetime.now())
289 if (loop.time() + 1.0) >= end_time:
290 break
291 await asyncio.sleep(1)
292
Yury Selivanov02a0a192017-12-14 09:42:21 -0500293 asyncio.run(display_date())
Yury Selivanov66f88282015-06-24 11:04:15 -0400294
Victor Stinner7f314ed2014-10-15 18:49:16 +0200295
Yury Selivanov512d7102018-09-17 19:35:30 -0400296Running Tasks Concurrently
297==========================
Victor Stinner7f314ed2014-10-15 18:49:16 +0200298
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700299.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100300
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700301 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700302 sequence *concurrently*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100303
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700304 If any awaitable in *aws* is a coroutine, it is automatically
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700305 scheduled as a Task.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100306
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700307 If all awaitables are completed successfully, the result is an
308 aggregate list of returned values. The order of result values
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700309 corresponds to the order of awaitables in *aws*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100310
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700311 If *return_exceptions* is ``False`` (default), the first
312 raised exception is immediately propagated to the task that
313 awaits on ``gather()``. Other awaitables in the *aws* sequence
314 **won't be cancelled** and will continue to run.
315
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700316 If *return_exceptions* is ``True``, exceptions are treated the
317 same as successful results, and aggregated in the result list.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100318
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700319 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov512d7102018-09-17 19:35:30 -0400320 (that have not completed yet) are also *cancelled*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100321
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700322 If any Task or Future from the *aws* sequence is *cancelled*, it is
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700323 treated as if it raised :exc:`CancelledError` -- the ``gather()``
324 call is **not** cancelled in this case. This is to prevent the
325 cancellation of one submitted Task/Future to cause other
326 Tasks/Futures to be cancelled.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700327
Yury Selivanov512d7102018-09-17 19:35:30 -0400328 .. _asyncio_example_gather:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100329
330 Example::
331
Yury Selivanov512d7102018-09-17 19:35:30 -0400332 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
Yury Selivanov512d7102018-09-17 19:35:30 -0400334 async def factorial(name, number):
335 f = 1
336 for i in range(2, number + 1):
337 print(f"Task {name}: Compute factorial({i})...")
338 await asyncio.sleep(1)
339 f *= i
340 print(f"Task {name}: factorial({number}) = {f}")
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341
Yury Selivanov512d7102018-09-17 19:35:30 -0400342 async def main():
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700343 # Schedule three calls *concurrently*:
Yury Selivanov512d7102018-09-17 19:35:30 -0400344 await asyncio.gather(
345 factorial("A", 2),
346 factorial("B", 3),
347 factorial("C", 4),
Miss Islington (bot)ee2ff1a2018-09-17 23:27:27 -0700348 )
Victor Stinnerea3183f2013-12-03 01:08:00 +0100349
Yury Selivanov512d7102018-09-17 19:35:30 -0400350 asyncio.run(main())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
Yury Selivanov512d7102018-09-17 19:35:30 -0400352 # Expected output:
353 #
354 # Task A: Compute factorial(2)...
355 # Task B: Compute factorial(2)...
356 # Task C: Compute factorial(2)...
357 # Task A: factorial(2) = 2
358 # Task B: Compute factorial(3)...
359 # Task C: Compute factorial(3)...
360 # Task B: factorial(3) = 6
361 # Task C: Compute factorial(4)...
362 # Task C: factorial(4) = 24
Victor Stinnerea3183f2013-12-03 01:08:00 +0100363
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700364 .. versionchanged:: 3.7
365 If the *gather* itself is cancelled, the cancellation is
366 propagated regardless of *return_exceptions*.
367
Victor Stinnerea3183f2013-12-03 01:08:00 +0100368
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700369Shielding From Cancellation
370===========================
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400371
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700372.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanove319ab02015-12-15 00:45:24 -0500373
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700374 Protect an :ref:`awaitable object <asyncio-awaitables>`
375 from being :meth:`cancelled <Task.cancel>`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200376
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700377 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100378
379 The statement::
380
Andrew Svetlov88743422017-12-11 17:35:49 +0200381 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100382
Yury Selivanov512d7102018-09-17 19:35:30 -0400383 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100384
Andrew Svetlov88743422017-12-11 17:35:49 +0200385 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100386
Yury Selivanov512d7102018-09-17 19:35:30 -0400387 *except* that if the coroutine containing it is cancelled, the
388 Task running in ``something()`` is not cancelled. From the point
389 of view of ``something()``, the cancellation did not happen.
390 Although its caller is still cancelled, so the "await" expression
391 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Yury Selivanov512d7102018-09-17 19:35:30 -0400393 If ``something()`` is cancelled by other means (i.e. from within
394 itself) that would also cancel ``shield()``.
395
396 If it is desired to completely ignore cancellation (not recommended)
397 the ``shield()`` function should be combined with a try/except
398 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100399
400 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200401 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402 except CancelledError:
403 res = None
404
Yury Selivanov950204d2016-05-16 16:23:00 -0400405
Yury Selivanov512d7102018-09-17 19:35:30 -0400406Timeouts
407========
408
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700409.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov512d7102018-09-17 19:35:30 -0400410
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700411 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700412 to complete with a timeout.
Yury Selivanov512d7102018-09-17 19:35:30 -0400413
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700414 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov512d7102018-09-17 19:35:30 -0400415
416 *timeout* can either be ``None`` or a float or int number of seconds
417 to wait for. If *timeout* is ``None``, block until the future
418 completes.
419
420 If a timeout occurs, it cancels the task and raises
421 :exc:`asyncio.TimeoutError`.
422
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700423 To avoid the task :meth:`cancellation <Task.cancel>`,
424 wrap it in :func:`shield`.
Yury Selivanov512d7102018-09-17 19:35:30 -0400425
426 The function will wait until the future is actually cancelled,
427 so the total wait time may exceed the *timeout*.
428
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700429 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov512d7102018-09-17 19:35:30 -0400430
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700431 The *loop* argument is deprecated and scheduled for removal
432 in Python 4.0.
433
Yury Selivanov512d7102018-09-17 19:35:30 -0400434 .. _asyncio_example_waitfor:
435
436 Example::
437
438 async def eternity():
439 # Sleep for one hour
440 await asyncio.sleep(3600)
441 print('yay!')
442
443 async def main():
444 # Wait for at most 1 second
445 try:
446 await asyncio.wait_for(eternity(), timeout=1.0)
447 except asyncio.TimeoutError:
448 print('timeout!')
449
450 asyncio.run(main())
451
452 # Expected output:
453 #
454 # timeout!
455
456 .. versionchanged:: 3.7
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700457 When *aw* is cancelled due to a timeout, ``wait_for`` waits
458 for *aw* to be cancelled. Previously, it raised
Yury Selivanov512d7102018-09-17 19:35:30 -0400459 :exc:`asyncio.TimeoutError` immediately.
460
461
462Waiting Primitives
463==================
464
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700465.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200466 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100467
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700468 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)3cc95572018-09-25 11:57:49 -0700469 set concurrently and block until the condition specified
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700470 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100471
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700472 If any awaitable in *aws* is a coroutine, it is automatically
Miss Islington (bot)3cc95572018-09-25 11:57:49 -0700473 scheduled as a Task. Passing coroutines objects to
474 ``wait()`` directly is deprecated as it leads to
475 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200476
Yury Selivanov512d7102018-09-17 19:35:30 -0400477 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100478
Miss Islington (bot)3cc95572018-09-25 11:57:49 -0700479 Usage::
480
481 done, pending = await asyncio.wait(aws)
482
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700483 The *loop* argument is deprecated and scheduled for removal
484 in Python 4.0.
485
Yury Selivanov512d7102018-09-17 19:35:30 -0400486 *timeout* (a float or int), if specified, can be used to control
487 the maximum number of seconds to wait before returning.
488
489 Note that this function does not raise :exc:`asyncio.TimeoutError`.
490 Futures or Tasks that aren't done when the timeout occurs are simply
491 returned in the second set.
492
493 *return_when* indicates when this function should return. It must
494 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100495
496 .. tabularcolumns:: |l|L|
497
498 +-----------------------------+----------------------------------------+
499 | Constant | Description |
500 +=============================+========================================+
501 | :const:`FIRST_COMPLETED` | The function will return when any |
502 | | future finishes or is cancelled. |
503 +-----------------------------+----------------------------------------+
504 | :const:`FIRST_EXCEPTION` | The function will return when any |
505 | | future finishes by raising an |
506 | | exception. If no future raises an |
507 | | exception then it is equivalent to |
508 | | :const:`ALL_COMPLETED`. |
509 +-----------------------------+----------------------------------------+
510 | :const:`ALL_COMPLETED` | The function will return when all |
511 | | futures finish or are cancelled. |
512 +-----------------------------+----------------------------------------+
513
Yury Selivanov512d7102018-09-17 19:35:30 -0400514 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
515 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100516
Miss Islington (bot)3cc95572018-09-25 11:57:49 -0700517 .. _asyncio_example_wait_coroutine:
518 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Miss Islington (bot)3cc95572018-09-25 11:57:49 -0700520 ``wait()`` schedules coroutines as Tasks automatically and later
521 returns those implicitly created Task objects in ``(done, pending)``
522 sets. Therefore the following code won't work as expected::
523
524 async def foo():
525 return 42
526
527 coro = foo()
528 done, pending = await asyncio.wait({coro})
529
530 if coro in done:
531 # This branch will never be run!
532
533 Here is how the above snippet can be fixed::
534
535 async def foo():
536 return 42
537
538 task = asyncio.create_task(foo())
539 done, pending = await asyncio.wait({task})
540
541 if task in done:
542 # Everything will work as expected now.
543
544 Passing coroutine objects to ``wait()`` directly is
545 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100546
Victor Stinnerea3183f2013-12-03 01:08:00 +0100547
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700548.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov512d7102018-09-17 19:35:30 -0400549
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700550 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700551 set concurrently. Return an iterator of :class:`Future` objects.
552 Each Future object returned represents the earliest result
553 from the set of the remaining awaitables.
Yury Selivanov512d7102018-09-17 19:35:30 -0400554
555 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
556 all Futures are done.
557
558 Example::
559
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700560 for f in as_completed(aws):
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700561 earliest_result = await f
Yury Selivanov512d7102018-09-17 19:35:30 -0400562 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100563
Victor Stinner3e09e322013-12-03 01:22:06 +0100564
Yury Selivanov512d7102018-09-17 19:35:30 -0400565Scheduling From Other Threads
566=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100567
Yury Selivanov512d7102018-09-17 19:35:30 -0400568.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100569
Yury Selivanov512d7102018-09-17 19:35:30 -0400570 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100571
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700572 Return a :class:`concurrent.futures.Future` to wait for the result
573 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100574
Yury Selivanov512d7102018-09-17 19:35:30 -0400575 This function is meant to be called from a different OS thread
576 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200577
Yury Selivanov512d7102018-09-17 19:35:30 -0400578 # Create a coroutine
579 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500580
Yury Selivanov512d7102018-09-17 19:35:30 -0400581 # Submit the coroutine to a given loop
582 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100583
Yury Selivanov512d7102018-09-17 19:35:30 -0400584 # Wait for the result with an optional timeout argument
585 assert future.result(timeout) == 3
586
587 If an exception is raised in the coroutine, the returned Future
588 will be notified. It can also be used to cancel the task in
589 the event loop::
590
591 try:
592 result = future.result(timeout)
593 except asyncio.TimeoutError:
594 print('The coroutine took too long, cancelling the task...')
595 future.cancel()
596 except Exception as exc:
597 print('The coroutine raised an exception: {!r}'.format(exc))
598 else:
599 print('The coroutine returned: {!r}'.format(result))
600
601 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
602 section of the documentation.
603
604 Unlike other asyncio functions this functions requires the *loop*
605 argument to be passed explicitly.
606
607 .. versionadded:: 3.5.1
608
609
610Introspection
611=============
612
613
614.. function:: current_task(loop=None)
615
616 Return the currently running :class:`Task` instance, or ``None`` if
617 no task is running.
618
619 If *loop* is ``None`` :func:`get_running_loop` is used to get
620 the current loop.
621
622 .. versionadded:: 3.7
623
624
625.. function:: all_tasks(loop=None)
626
627 Return a set of not yet finished :class:`Task` objects run by
628 the loop.
629
630 If *loop* is ``None``, :func:`get_running_loop` is used for getting
631 current loop.
632
633 .. versionadded:: 3.7
634
635
636Task Object
637===========
638
639.. class:: Task(coro, \*, loop=None)
640
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700641 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov512d7102018-09-17 19:35:30 -0400642 :ref:`coroutine <coroutine>`. Not thread-safe.
643
644 Tasks are used to run coroutines in event loops.
645 If a coroutine awaits on a Future, the Task suspends
646 the execution of the coroutine and waits for the completion
647 of the Future. When the Future is *done*, the execution of
648 the wrapped coroutine resumes.
649
650 Event loops use cooperative scheduling: an event loop runs
651 one Task at a time. While a Task awaits for the completion of a
652 Future, the event loop runs other Tasks, callbacks, or performs
653 IO operations.
654
655 Use the high-level :func:`asyncio.create_task` function to create
656 Tasks, or the low-level :meth:`loop.create_task` or
657 :func:`ensure_future` functions. Manual instantiation of Tasks
658 is discouraged.
659
660 To cancel a running Task use the :meth:`cancel` method. Calling it
661 will cause the Task to throw a :exc:`CancelledError` exception into
662 the wrapped coroutine. If a coroutine is awaiting on a Future
663 object during cancellation, the Future object will be cancelled.
664
665 :meth:`cancelled` can be used to check if the Task was cancelled.
666 The method returns ``True`` if the wrapped coroutine did not
667 suppress the :exc:`CancelledError` exception and was actually
668 cancelled.
669
670 :class:`asyncio.Task` inherits from :class:`Future` all of its
671 APIs except :meth:`Future.set_result` and
672 :meth:`Future.set_exception`.
673
674 Tasks support the :mod:`contextvars` module. When a Task
675 is created it copies the current context and later runs its
676 coroutine in the copied context.
Miss Islington (bot)d8948c52018-05-29 15:37:06 -0700677
678 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400679 Added support for the :mod:`contextvars` module.
680
681 .. method:: cancel()
682
683 Request the Task to be cancelled.
684
685 This arranges for a :exc:`CancelledError` exception to be thrown
686 into the wrapped coroutine on the next cycle of the event loop.
687
688 The coroutine then has a chance to clean up or even deny the
689 request by suppressing the exception with a :keyword:`try` ...
690 ... ``except CancelledError`` ... :keyword:`finally` block.
691 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
692 not guarantee that the Task will be cancelled, although
693 suppressing cancellation completely is not common and is actively
694 discouraged.
695
696 .. _asyncio_example_task_cancel:
697
698 The following example illustrates how coroutines can intercept
699 the cancellation request::
700
701 async def cancel_me():
702 print('cancel_me(): before sleep')
703
704 try:
705 # Wait for 1 hour
706 await asyncio.sleep(3600)
707 except asyncio.CancelledError:
708 print('cancel_me(): cancel sleep')
709 raise
710 finally:
711 print('cancel_me(): after sleep')
712
713 async def main():
714 # Create a "cancel_me" Task
715 task = asyncio.create_task(cancel_me())
716
717 # Wait for 1 second
718 await asyncio.sleep(1)
719
720 task.cancel()
721 try:
722 await task
723 except asyncio.CancelledError:
724 print("main(): cancel_me is cancelled now")
725
726 asyncio.run(main())
727
728 # Expected output:
729 #
730 # cancel_me(): before sleep
731 # cancel_me(): cancel sleep
732 # cancel_me(): after sleep
733 # main(): cancel_me is cancelled now
734
735 .. method:: cancelled()
736
737 Return ``True`` if the Task is *cancelled*.
738
739 The Task is *cancelled* when the cancellation was requested with
740 :meth:`cancel` and the wrapped coroutine propagated the
741 :exc:`CancelledError` exception thrown into it.
742
743 .. method:: done()
744
745 Return ``True`` if the Task is *done*.
746
747 A Task is *done* when the wrapped coroutine either returned
748 a value, raised an exception, or the Task was cancelled.
749
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700750 .. method:: result()
751
752 Return the result of the Task.
753
754 If the Task is *done*, the result of the wrapped coroutine
755 is returned (or if the coroutine raised an exception, that
756 exception is re-raised.)
757
758 If the Task has been *cancelled*, this method raises
759 a :exc:`CancelledError` exception.
760
761 If the Task's result isn't yet available, this method raises
762 a :exc:`InvalidStateError` exception.
763
764 .. method:: exception()
765
766 Return the exception of the Task.
767
768 If the wrapped coroutine raised an exception that exception
769 is returned. If the wrapped coroutine returned normally
770 this method returns ``None``.
771
772 If the Task has been *cancelled*, this method raises a
773 :exc:`CancelledError` exception.
774
775 If the Task isn't *done* yet, this method raises an
776 :exc:`InvalidStateError` exception.
777
778 .. method:: add_done_callback(callback, *, context=None)
779
780 Add a callback to be run when the Task is *done*.
781
782 This method should only be used in low-level callback-based code.
783
784 See the documentation of :meth:`Future.add_done_callback`
785 for more details.
786
787 .. method:: remove_done_callback(callback)
788
789 Remove *callback* from the callbacks list.
790
791 This method should only be used in low-level callback-based code.
792
793 See the documentation of :meth:`Future.remove_done_callback`
794 for more details.
795
Yury Selivanov512d7102018-09-17 19:35:30 -0400796 .. method:: get_stack(\*, limit=None)
797
798 Return the list of stack frames for this Task.
799
800 If the wrapped coroutine is not done, this returns the stack
801 where it is suspended. If the coroutine has completed
802 successfully or was cancelled, this returns an empty list.
803 If the coroutine was terminated by an exception, this returns
804 the list of traceback frames.
805
806 The frames are always ordered from oldest to newest.
807
808 Only one stack frame is returned for a suspended coroutine.
809
810 The optional *limit* argument sets the maximum number of frames
811 to return; by default all available frames are returned.
812 The ordering of the returned list differs depending on whether
813 a stack or a traceback is returned: the newest frames of a
814 stack are returned, but the oldest frames of a traceback are
815 returned. (This matches the behavior of the traceback module.)
816
817 .. method:: print_stack(\*, limit=None, file=None)
818
819 Print the stack or traceback for this Task.
820
821 This produces output similar to that of the traceback module
822 for the frames retrieved by :meth:`get_stack`.
823
824 The *limit* argument is passed to :meth:`get_stack` directly.
825
826 The *file* argument is an I/O stream to which the output
827 is written; by default output is written to :data:`sys.stderr`.
828
829 .. classmethod:: all_tasks(loop=None)
830
831 Return a set of all tasks for an event loop.
832
833 By default all tasks for the current event loop are returned.
834 If *loop* is ``None``, the :func:`get_event_loop` function
835 is used to get the current loop.
836
837 This method is **deprecated** and will be removed in
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700838 Python 3.9. Use the :func:`asyncio.all_tasks` function instead.
Yury Selivanov512d7102018-09-17 19:35:30 -0400839
840 .. classmethod:: current_task(loop=None)
841
842 Return the currently running task or ``None``.
843
844 If *loop* is ``None``, the :func:`get_event_loop` function
845 is used to get the current loop.
846
847 This method is **deprecated** and will be removed in
Miss Islington (bot)e45662c2018-09-21 13:35:34 -0700848 Python 3.9. Use the :func:`asyncio.current_task` function
849 instead.
Yury Selivanov512d7102018-09-17 19:35:30 -0400850
851
852.. _asyncio_generator_based_coro:
853
854Generator-based Coroutines
855==========================
856
857.. note::
858
859 Support for generator-based coroutines is **deprecated** and
860 is scheduled for removal in Python 4.0.
861
862Generator-based coroutines predate async/await syntax. They are
863Python generators that use ``yield from`` expressions to await
864on Futures and other coroutines.
865
866Generator-based coroutines should be decorated with
867:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
868enforced.
869
870
871.. decorator:: coroutine
872
873 Decorator to mark generator-based coroutines.
874
875 This decorator enables legacy generator-based coroutines to be
876 compatible with async/await code::
877
878 @asyncio.coroutine
879 def old_style_coroutine():
880 yield from asyncio.sleep(1)
881
882 async def main():
883 await old_style_coroutine()
884
885 This decorator is **deprecated** and is scheduled for removal in
886 Python 4.0.
887
888 This decorator should not be used for :keyword:`async def`
889 coroutines.
890
891.. function:: iscoroutine(obj)
892
893 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
894
895 This method is different from :func:`inspect.iscoroutine` because
896 it returns ``True`` for generator-based coroutines decorated with
897 :func:`@coroutine <coroutine>`.
898
899.. function:: iscoroutinefunction(func)
900
901 Return ``True`` if *func* is a :ref:`coroutine function
902 <coroutine>`.
903
904 This method is different from :func:`inspect.iscoroutinefunction`
905 because it returns ``True`` for generator-based coroutine functions
906 decorated with :func:`@coroutine <coroutine>`.