blob: 155887a3ab3af9dc2abf6e58bab48e2fc088b665 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov3faaa882018-09-14 13:32:07 -07003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov3faaa882018-09-14 13:32:07 -07008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov3faaa882018-09-14 13:32:07 -070011.. 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 Selivanov3faaa882018-09-14 13:32:07 -070019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov3faaa882018-09-14 13:32:07 -070021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Yury Selivanovb042cf12018-09-18 02:47:54 -040023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov3faaa882018-09-14 13:32:07 -070026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov3faaa882018-09-14 13:32:07 -070028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov3faaa882018-09-14 13:32:07 -070033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov3faaa882018-09-14 13:32:07 -070037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov3faaa882018-09-14 13:32:07 -070040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Boštjan Mejak1d5bdef2019-05-19 11:01:36 +020043To actually run a coroutine, asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040045* The :func:`asyncio.run` function to run the top-level
Yury Selivanov3faaa882018-09-14 13:32:07 -070046 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040048* Awaiting on a coroutine. The following snippet of code will
Yury Selivanov3faaa882018-09-14 13:32:07 -070049 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 Selivanov3faaa882018-09-14 13:32:07 -070052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov3faaa882018-09-14 13:32:07 -070055 async def say_after(delay, what):
56 await asyncio.sleep(delay)
57 print(what)
58
59 async def main():
Mariatta9f43fbb2018-10-24 15:37:12 -070060 print(f"started at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070061
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
Mariatta9f43fbb2018-10-24 15:37:12 -070065 print(f"finished at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070066
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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040076* The :func:`asyncio.create_task` function to run coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070077 concurrently as asyncio :class:`Tasks <Task>`.
78
Danny Hermes7bfbda42018-09-17 21:49:21 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070080 *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
Mariatta9f43fbb2018-10-24 15:37:12 -070089 print(f"started at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070090
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
Mariatta9f43fbb2018-10-24 15:37:12 -070096 print(f"finished at {time.strftime('%X')}")
Yury Selivanov3faaa882018-09-14 13:32:07 -070097
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
Yury Selivanov47150392018-09-18 17:55:44 -0400106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
Yury Selivanove247b462018-09-20 12:43:59 -0400112We 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**.
Yury Selivanov47150392018-09-18 17:55:44 -0400118
119
Yury Selivanove247b462018-09-20 12:43:59 -0400120.. rubric:: Coroutines
Yury Selivanov47150392018-09-18 17:55:44 -0400121
Yury Selivanove247b462018-09-20 12:43:59 -0400122Python coroutines are *awaitables* and therefore can be awaited from
123other coroutines::
124
125 import asyncio
Yury Selivanov47150392018-09-18 17:55:44 -0400126
127 async def nested():
128 return 42
129
130 async def main():
Yury Selivanove247b462018-09-20 12:43:59 -0400131 # Nothing happens if we just call "nested()".
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400132 # A coroutine object is created but not awaited,
133 # so it *won't run at all*.
Yury Selivanove247b462018-09-20 12:43:59 -0400134 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
Yury Selivanov47150392018-09-18 17:55:44 -0400156
157*Tasks* are used to schedule coroutines *concurrently*.
Yury Selivanov47150392018-09-18 17:55:44 -0400158
Yury Selivanove247b462018-09-20 12:43:59 -0400159When a coroutine is wrapped into a *Task* with functions like
160:func:`asyncio.create_task` the coroutine is automatically
161scheduled to run soon::
Yury Selivanov3faaa882018-09-14 13:32:07 -0700162
Yury Selivanove247b462018-09-20 12:43:59 -0400163 import asyncio
Yury Selivanov3faaa882018-09-14 13:32:07 -0700164
Yury Selivanove247b462018-09-20 12:43:59 -0400165 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
Yury Selivanov47150392018-09-18 17:55:44 -0400180.. rubric:: Futures
181
Yury Selivanove247b462018-09-20 12:43:59 -0400182A :class:`Future` is a special **low-level** awaitable object that
183represents an **eventual result** of an asynchronous operation.
Yury Selivanov47150392018-09-18 17:55:44 -0400184
Yury Selivanove247b462018-09-20 12:43:59 -0400185When a Future object is *awaited* it means that the coroutine will
186wait until the Future is resolved in some other place.
187
Yury Selivanov47150392018-09-18 17:55:44 -0400188Future objects in asyncio are needed to allow callback-based code
189to be used with async/await.
190
Yury Selivanove247b462018-09-20 12:43:59 -0400191Normally **there is no need** to create Future objects at the
Yury Selivanov47150392018-09-18 17:55:44 -0400192application level code.
193
194Future objects, sometimes exposed by libraries and some asyncio
Yury Selivanove247b462018-09-20 12:43:59 -0400195APIs, can be awaited::
Yury Selivanov47150392018-09-18 17:55:44 -0400196
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
Yury Selivanove247b462018-09-20 12:43:59 -0400206A good example of a low-level function that returns a Future object
207is :meth:`loop.run_in_executor`.
208
Yury Selivanov47150392018-09-18 17:55:44 -0400209
Yury Selivanov3faaa882018-09-14 13:32:07 -0700210Running an asyncio Program
211==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100212
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -0400213.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500214
Kyle Stanleye4070132019-09-30 20:12:21 -0400215 Execute the :term:`coroutine` *coro* and return the result.
216
Yury Selivanov02a0a192017-12-14 09:42:21 -0500217 This function runs the passed coroutine, taking care of
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400218 managing the asyncio event loop, *finalizing asynchronous
219 generators*, and closing the threadpool.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500220
221 This function cannot be called when another asyncio event loop is
222 running in the same thread.
223
Yury Selivanov3faaa882018-09-14 13:32:07 -0700224 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500225
226 This function always creates a new event loop and closes it at
227 the end. It should be used as a main entry point for asyncio
228 programs, and should ideally only be called once.
229
Emmanuel Arias17deb162019-09-25 05:53:49 -0300230 Example::
231
232 async def main():
233 await asyncio.sleep(1)
234 print('hello')
235
236 asyncio.run(main())
237
Yury Selivanov02a0a192017-12-14 09:42:21 -0500238 .. versionadded:: 3.7
239
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400240 .. versionchanged:: 3.9
241 Updated to use :meth:`loop.shutdown_default_executor`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500242
Yury Selivanov3faaa882018-09-14 13:32:07 -0700243Creating Tasks
244==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100245
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300246.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200247
Yury Selivanove247b462018-09-20 12:43:59 -0400248 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
249 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300250
251 If *name* is not ``None``, it is set as the name of the task using
252 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200253
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400254 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200255 :exc:`RuntimeError` is raised if there is no running loop in
256 current thread.
257
Yury Selivanov47150392018-09-18 17:55:44 -0400258 This function has been **added in Python 3.7**. Prior to
259 Python 3.7, the low-level :func:`asyncio.ensure_future` function
260 can be used instead::
261
262 async def coro():
263 ...
264
265 # In Python 3.7+
266 task = asyncio.create_task(coro())
267 ...
268
269 # This works in all Python versions but is less readable
270 task = asyncio.ensure_future(coro())
271 ...
272
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200273 .. versionadded:: 3.7
274
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300275 .. versionchanged:: 3.8
276 Added the ``name`` parameter.
277
Victor Stinnerea3183f2013-12-03 01:08:00 +0100278
Yury Selivanov3faaa882018-09-14 13:32:07 -0700279Sleeping
280========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200281
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100282.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
Yury Selivanov3faaa882018-09-14 13:32:07 -0700284 Block for *delay* seconds.
285
286 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800287 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100288
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200289 ``sleep()`` always suspends the current task, allowing other tasks
290 to run.
291
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700292 .. deprecated-removed:: 3.8 3.10
293 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400294
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700295 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100296
Yury Selivanov3faaa882018-09-14 13:32:07 -0700297 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400298 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100299
Yury Selivanov3faaa882018-09-14 13:32:07 -0700300 import asyncio
301 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100302
Yury Selivanov3faaa882018-09-14 13:32:07 -0700303 async def display_date():
304 loop = asyncio.get_running_loop()
305 end_time = loop.time() + 5.0
306 while True:
307 print(datetime.datetime.now())
308 if (loop.time() + 1.0) >= end_time:
309 break
310 await asyncio.sleep(1)
311
312 asyncio.run(display_date())
313
314
315Running Tasks Concurrently
316==========================
317
Yury Selivanove247b462018-09-20 12:43:59 -0400318.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700319
Yury Selivanove247b462018-09-20 12:43:59 -0400320 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400321 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700322
Yury Selivanove247b462018-09-20 12:43:59 -0400323 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400324 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700325
Yury Selivanov47150392018-09-18 17:55:44 -0400326 If all awaitables are completed successfully, the result is an
327 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400328 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700329
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400330 If *return_exceptions* is ``False`` (default), the first
331 raised exception is immediately propagated to the task that
332 awaits on ``gather()``. Other awaitables in the *aws* sequence
333 **won't be cancelled** and will continue to run.
334
Yury Selivanov47150392018-09-18 17:55:44 -0400335 If *return_exceptions* is ``True``, exceptions are treated the
336 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700337
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400338 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700339 (that have not completed yet) are also *cancelled*.
340
Yury Selivanove247b462018-09-20 12:43:59 -0400341 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400342 treated as if it raised :exc:`CancelledError` -- the ``gather()``
343 call is **not** cancelled in this case. This is to prevent the
344 cancellation of one submitted Task/Future to cause other
345 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700346
Andrew Svetlova4888792019-09-12 15:40:40 +0300347 .. deprecated-removed:: 3.8 3.10
348 The *loop* parameter.
349
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700350 .. _asyncio_example_gather:
351
Yury Selivanov3faaa882018-09-14 13:32:07 -0700352 Example::
353
354 import asyncio
355
356 async def factorial(name, number):
357 f = 1
358 for i in range(2, number + 1):
359 print(f"Task {name}: Compute factorial({i})...")
360 await asyncio.sleep(1)
361 f *= i
362 print(f"Task {name}: factorial({number}) = {f}")
363
364 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400365 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700366 await asyncio.gather(
367 factorial("A", 2),
368 factorial("B", 3),
369 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200370 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700371
372 asyncio.run(main())
373
374 # Expected output:
375 #
376 # Task A: Compute factorial(2)...
377 # Task B: Compute factorial(2)...
378 # Task C: Compute factorial(2)...
379 # Task A: factorial(2) = 2
380 # Task B: Compute factorial(3)...
381 # Task C: Compute factorial(3)...
382 # Task B: factorial(3) = 6
383 # Task C: Compute factorial(4)...
384 # Task C: factorial(4) = 24
385
Yury Selivanov47150392018-09-18 17:55:44 -0400386 .. versionchanged:: 3.7
387 If the *gather* itself is cancelled, the cancellation is
388 propagated regardless of *return_exceptions*.
389
Yury Selivanov3faaa882018-09-14 13:32:07 -0700390
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400391Shielding From Cancellation
392===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700393
Yury Selivanove247b462018-09-20 12:43:59 -0400394.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700395
Yury Selivanov47150392018-09-18 17:55:44 -0400396 Protect an :ref:`awaitable object <asyncio-awaitables>`
397 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700398
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400399 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100400
401 The statement::
402
Andrew Svetlov88743422017-12-11 17:35:49 +0200403 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100404
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400405 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
Andrew Svetlov88743422017-12-11 17:35:49 +0200407 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100408
Yury Selivanov3faaa882018-09-14 13:32:07 -0700409 *except* that if the coroutine containing it is cancelled, the
410 Task running in ``something()`` is not cancelled. From the point
411 of view of ``something()``, the cancellation did not happen.
412 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400413 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
Yury Selivanov3faaa882018-09-14 13:32:07 -0700415 If ``something()`` is cancelled by other means (i.e. from within
416 itself) that would also cancel ``shield()``.
417
418 If it is desired to completely ignore cancellation (not recommended)
419 the ``shield()`` function should be combined with a try/except
420 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100421
422 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200423 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100424 except CancelledError:
425 res = None
426
Andrew Svetlova4888792019-09-12 15:40:40 +0300427 .. deprecated-removed:: 3.8 3.10
428 The *loop* parameter.
429
Yury Selivanov950204d2016-05-16 16:23:00 -0400430
Yury Selivanov3faaa882018-09-14 13:32:07 -0700431Timeouts
432========
433
Yury Selivanove247b462018-09-20 12:43:59 -0400434.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700435
Yury Selivanove247b462018-09-20 12:43:59 -0400436 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400437 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700438
Yury Selivanove247b462018-09-20 12:43:59 -0400439 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700440
441 *timeout* can either be ``None`` or a float or int number of seconds
442 to wait for. If *timeout* is ``None``, block until the future
443 completes.
444
445 If a timeout occurs, it cancels the task and raises
446 :exc:`asyncio.TimeoutError`.
447
Yury Selivanov47150392018-09-18 17:55:44 -0400448 To avoid the task :meth:`cancellation <Task.cancel>`,
449 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700450
451 The function will wait until the future is actually cancelled,
452 so the total wait time may exceed the *timeout*.
453
Yury Selivanove247b462018-09-20 12:43:59 -0400454 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700455
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700456 .. deprecated-removed:: 3.8 3.10
457 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400458
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700459 .. _asyncio_example_waitfor:
460
Yury Selivanov3faaa882018-09-14 13:32:07 -0700461 Example::
462
463 async def eternity():
464 # Sleep for one hour
465 await asyncio.sleep(3600)
466 print('yay!')
467
468 async def main():
469 # Wait for at most 1 second
470 try:
471 await asyncio.wait_for(eternity(), timeout=1.0)
472 except asyncio.TimeoutError:
473 print('timeout!')
474
475 asyncio.run(main())
476
477 # Expected output:
478 #
479 # timeout!
480
481 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400482 When *aw* is cancelled due to a timeout, ``wait_for`` waits
483 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700484 :exc:`asyncio.TimeoutError` immediately.
485
486
487Waiting Primitives
488==================
489
Yury Selivanove247b462018-09-20 12:43:59 -0400490.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200491 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100492
Yury Selivanove247b462018-09-20 12:43:59 -0400493 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov996859a2018-09-25 14:51:21 -0400494 set concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400495 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100496
Yury Selivanov3faaa882018-09-14 13:32:07 -0700497 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100498
Yury Selivanov996859a2018-09-25 14:51:21 -0400499 Usage::
500
501 done, pending = await asyncio.wait(aws)
502
Yury Selivanov3faaa882018-09-14 13:32:07 -0700503 *timeout* (a float or int), if specified, can be used to control
504 the maximum number of seconds to wait before returning.
505
506 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400507 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700508 returned in the second set.
509
510 *return_when* indicates when this function should return. It must
511 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100512
513 .. tabularcolumns:: |l|L|
514
515 +-----------------------------+----------------------------------------+
516 | Constant | Description |
517 +=============================+========================================+
518 | :const:`FIRST_COMPLETED` | The function will return when any |
519 | | future finishes or is cancelled. |
520 +-----------------------------+----------------------------------------+
521 | :const:`FIRST_EXCEPTION` | The function will return when any |
522 | | future finishes by raising an |
523 | | exception. If no future raises an |
524 | | exception then it is equivalent to |
525 | | :const:`ALL_COMPLETED`. |
526 +-----------------------------+----------------------------------------+
527 | :const:`ALL_COMPLETED` | The function will return when all |
528 | | futures finish or are cancelled. |
529 +-----------------------------+----------------------------------------+
530
Yury Selivanov3faaa882018-09-14 13:32:07 -0700531 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
532 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100533
Andrew Svetlova4888792019-09-12 15:40:40 +0300534 .. deprecated:: 3.8
535
536 If any awaitable in *aws* is a coroutine, it is automatically
537 scheduled as a Task. Passing coroutines objects to
538 ``wait()`` directly is deprecated as it leads to
539 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
540
541 .. deprecated-removed:: 3.8 3.10
542
543 The *loop* parameter.
544
Yury Selivanov996859a2018-09-25 14:51:21 -0400545 .. _asyncio_example_wait_coroutine:
546 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100547
Yury Selivanov996859a2018-09-25 14:51:21 -0400548 ``wait()`` schedules coroutines as Tasks automatically and later
549 returns those implicitly created Task objects in ``(done, pending)``
550 sets. Therefore the following code won't work as expected::
551
552 async def foo():
553 return 42
554
555 coro = foo()
556 done, pending = await asyncio.wait({coro})
557
558 if coro in done:
559 # This branch will never be run!
560
561 Here is how the above snippet can be fixed::
562
563 async def foo():
564 return 42
565
566 task = asyncio.create_task(foo())
567 done, pending = await asyncio.wait({task})
568
569 if task in done:
570 # Everything will work as expected now.
571
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700572 .. deprecated:: 3.8
573
Yury Selivanov996859a2018-09-25 14:51:21 -0400574 Passing coroutine objects to ``wait()`` directly is
575 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100576
Victor Stinnerea3183f2013-12-03 01:08:00 +0100577
Yury Selivanove247b462018-09-20 12:43:59 -0400578.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700579
Yury Selivanove247b462018-09-20 12:43:59 -0400580 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400581 set concurrently. Return an iterator of :class:`Future` objects.
582 Each Future object returned represents the earliest result
583 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700584
585 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
586 all Futures are done.
587
Andrew Svetlova4888792019-09-12 15:40:40 +0300588 .. deprecated-removed:: 3.8 3.10
589 The *loop* parameter.
590
Yury Selivanov3faaa882018-09-14 13:32:07 -0700591 Example::
592
Yury Selivanove247b462018-09-20 12:43:59 -0400593 for f in as_completed(aws):
Yury Selivanov47150392018-09-18 17:55:44 -0400594 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700595 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100596
Victor Stinner3e09e322013-12-03 01:22:06 +0100597
Yury Selivanov3faaa882018-09-14 13:32:07 -0700598Scheduling From Other Threads
599=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100600
Yury Selivanov3faaa882018-09-14 13:32:07 -0700601.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100602
Yury Selivanov3faaa882018-09-14 13:32:07 -0700603 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100604
Yury Selivanov47150392018-09-18 17:55:44 -0400605 Return a :class:`concurrent.futures.Future` to wait for the result
606 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100607
Yury Selivanov3faaa882018-09-14 13:32:07 -0700608 This function is meant to be called from a different OS thread
609 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200610
Yury Selivanov3faaa882018-09-14 13:32:07 -0700611 # Create a coroutine
612 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500613
Yury Selivanov3faaa882018-09-14 13:32:07 -0700614 # Submit the coroutine to a given loop
615 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100616
Yury Selivanov3faaa882018-09-14 13:32:07 -0700617 # Wait for the result with an optional timeout argument
618 assert future.result(timeout) == 3
619
620 If an exception is raised in the coroutine, the returned Future
621 will be notified. It can also be used to cancel the task in
622 the event loop::
623
624 try:
625 result = future.result(timeout)
626 except asyncio.TimeoutError:
627 print('The coroutine took too long, cancelling the task...')
628 future.cancel()
629 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700630 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700631 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700632 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700633
634 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
635 section of the documentation.
636
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530637 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700638 argument to be passed explicitly.
639
640 .. versionadded:: 3.5.1
641
642
643Introspection
644=============
645
646
647.. function:: current_task(loop=None)
648
649 Return the currently running :class:`Task` instance, or ``None`` if
650 no task is running.
651
652 If *loop* is ``None`` :func:`get_running_loop` is used to get
653 the current loop.
654
655 .. versionadded:: 3.7
656
657
658.. function:: all_tasks(loop=None)
659
660 Return a set of not yet finished :class:`Task` objects run by
661 the loop.
662
663 If *loop* is ``None``, :func:`get_running_loop` is used for getting
664 current loop.
665
666 .. versionadded:: 3.7
667
668
669Task Object
670===========
671
672.. class:: Task(coro, \*, loop=None, name=None)
673
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400674 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700675 :ref:`coroutine <coroutine>`. Not thread-safe.
676
677 Tasks are used to run coroutines in event loops.
678 If a coroutine awaits on a Future, the Task suspends
679 the execution of the coroutine and waits for the completion
680 of the Future. When the Future is *done*, the execution of
681 the wrapped coroutine resumes.
682
683 Event loops use cooperative scheduling: an event loop runs
684 one Task at a time. While a Task awaits for the completion of a
685 Future, the event loop runs other Tasks, callbacks, or performs
686 IO operations.
687
688 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400689 Tasks, or the low-level :meth:`loop.create_task` or
690 :func:`ensure_future` functions. Manual instantiation of Tasks
691 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700692
693 To cancel a running Task use the :meth:`cancel` method. Calling it
694 will cause the Task to throw a :exc:`CancelledError` exception into
695 the wrapped coroutine. If a coroutine is awaiting on a Future
696 object during cancellation, the Future object will be cancelled.
697
698 :meth:`cancelled` can be used to check if the Task was cancelled.
699 The method returns ``True`` if the wrapped coroutine did not
700 suppress the :exc:`CancelledError` exception and was actually
701 cancelled.
702
703 :class:`asyncio.Task` inherits from :class:`Future` all of its
704 APIs except :meth:`Future.set_result` and
705 :meth:`Future.set_exception`.
706
707 Tasks support the :mod:`contextvars` module. When a Task
708 is created it copies the current context and later runs its
709 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400710
711 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700712 Added support for the :mod:`contextvars` module.
713
714 .. versionchanged:: 3.8
715 Added the ``name`` parameter.
716
Andrew Svetlova4888792019-09-12 15:40:40 +0300717 .. deprecated-removed:: 3.8 3.10
718 The *loop* parameter.
719
Yury Selivanov3faaa882018-09-14 13:32:07 -0700720 .. method:: cancel()
721
722 Request the Task to be cancelled.
723
724 This arranges for a :exc:`CancelledError` exception to be thrown
725 into the wrapped coroutine on the next cycle of the event loop.
726
727 The coroutine then has a chance to clean up or even deny the
728 request by suppressing the exception with a :keyword:`try` ...
729 ... ``except CancelledError`` ... :keyword:`finally` block.
730 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
731 not guarantee that the Task will be cancelled, although
732 suppressing cancellation completely is not common and is actively
733 discouraged.
734
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700735 .. _asyncio_example_task_cancel:
736
Yury Selivanov3faaa882018-09-14 13:32:07 -0700737 The following example illustrates how coroutines can intercept
738 the cancellation request::
739
740 async def cancel_me():
741 print('cancel_me(): before sleep')
742
743 try:
744 # Wait for 1 hour
745 await asyncio.sleep(3600)
746 except asyncio.CancelledError:
747 print('cancel_me(): cancel sleep')
748 raise
749 finally:
750 print('cancel_me(): after sleep')
751
752 async def main():
753 # Create a "cancel_me" Task
754 task = asyncio.create_task(cancel_me())
755
756 # Wait for 1 second
757 await asyncio.sleep(1)
758
759 task.cancel()
760 try:
761 await task
762 except asyncio.CancelledError:
763 print("main(): cancel_me is cancelled now")
764
765 asyncio.run(main())
766
767 # Expected output:
768 #
769 # cancel_me(): before sleep
770 # cancel_me(): cancel sleep
771 # cancel_me(): after sleep
772 # main(): cancel_me is cancelled now
773
774 .. method:: cancelled()
775
776 Return ``True`` if the Task is *cancelled*.
777
778 The Task is *cancelled* when the cancellation was requested with
779 :meth:`cancel` and the wrapped coroutine propagated the
780 :exc:`CancelledError` exception thrown into it.
781
782 .. method:: done()
783
784 Return ``True`` if the Task is *done*.
785
786 A Task is *done* when the wrapped coroutine either returned
787 a value, raised an exception, or the Task was cancelled.
788
Yury Selivanove247b462018-09-20 12:43:59 -0400789 .. method:: result()
790
791 Return the result of the Task.
792
793 If the Task is *done*, the result of the wrapped coroutine
794 is returned (or if the coroutine raised an exception, that
795 exception is re-raised.)
796
797 If the Task has been *cancelled*, this method raises
798 a :exc:`CancelledError` exception.
799
800 If the Task's result isn't yet available, this method raises
801 a :exc:`InvalidStateError` exception.
802
803 .. method:: exception()
804
805 Return the exception of the Task.
806
807 If the wrapped coroutine raised an exception that exception
808 is returned. If the wrapped coroutine returned normally
809 this method returns ``None``.
810
811 If the Task has been *cancelled*, this method raises a
812 :exc:`CancelledError` exception.
813
814 If the Task isn't *done* yet, this method raises an
815 :exc:`InvalidStateError` exception.
816
817 .. method:: add_done_callback(callback, *, context=None)
818
819 Add a callback to be run when the Task is *done*.
820
821 This method should only be used in low-level callback-based code.
822
823 See the documentation of :meth:`Future.add_done_callback`
824 for more details.
825
826 .. method:: remove_done_callback(callback)
827
828 Remove *callback* from the callbacks list.
829
830 This method should only be used in low-level callback-based code.
831
832 See the documentation of :meth:`Future.remove_done_callback`
833 for more details.
834
Yury Selivanov3faaa882018-09-14 13:32:07 -0700835 .. method:: get_stack(\*, limit=None)
836
837 Return the list of stack frames for this Task.
838
839 If the wrapped coroutine is not done, this returns the stack
840 where it is suspended. If the coroutine has completed
841 successfully or was cancelled, this returns an empty list.
842 If the coroutine was terminated by an exception, this returns
843 the list of traceback frames.
844
845 The frames are always ordered from oldest to newest.
846
847 Only one stack frame is returned for a suspended coroutine.
848
849 The optional *limit* argument sets the maximum number of frames
850 to return; by default all available frames are returned.
851 The ordering of the returned list differs depending on whether
852 a stack or a traceback is returned: the newest frames of a
853 stack are returned, but the oldest frames of a traceback are
854 returned. (This matches the behavior of the traceback module.)
855
856 .. method:: print_stack(\*, limit=None, file=None)
857
858 Print the stack or traceback for this Task.
859
860 This produces output similar to that of the traceback module
861 for the frames retrieved by :meth:`get_stack`.
862
863 The *limit* argument is passed to :meth:`get_stack` directly.
864
865 The *file* argument is an I/O stream to which the output
866 is written; by default output is written to :data:`sys.stderr`.
867
Alex Grönholm98ef9202019-05-30 18:30:09 +0300868 .. method:: get_coro()
869
870 Return the coroutine object wrapped by the :class:`Task`.
871
872 .. versionadded:: 3.8
873
Yury Selivanov3faaa882018-09-14 13:32:07 -0700874 .. method:: get_name()
875
876 Return the name of the Task.
877
878 If no name has been explicitly assigned to the Task, the default
879 asyncio Task implementation generates a default name during
880 instantiation.
881
882 .. versionadded:: 3.8
883
884 .. method:: set_name(value)
885
886 Set the name of the Task.
887
888 The *value* argument can be any object, which is then
889 converted to a string.
890
891 In the default Task implementation, the name will be visible
892 in the :func:`repr` output of a task object.
893
894 .. versionadded:: 3.8
895
896 .. classmethod:: all_tasks(loop=None)
897
898 Return a set of all tasks for an event loop.
899
900 By default all tasks for the current event loop are returned.
901 If *loop* is ``None``, the :func:`get_event_loop` function
902 is used to get the current loop.
903
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700904 .. deprecated-removed:: 3.7 3.9
905
906 Do not call this as a task method. Use the :func:`asyncio.all_tasks`
907 function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700908
909 .. classmethod:: current_task(loop=None)
910
911 Return the currently running task or ``None``.
912
913 If *loop* is ``None``, the :func:`get_event_loop` function
914 is used to get the current loop.
915
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700916 .. deprecated-removed:: 3.7 3.9
917
918 Do not call this as a task method. Use the
919 :func:`asyncio.current_task` function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700920
921
922.. _asyncio_generator_based_coro:
923
924Generator-based Coroutines
925==========================
926
927.. note::
928
929 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -0400930 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700931
932Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400933Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700934on Futures and other coroutines.
935
936Generator-based coroutines should be decorated with
937:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
938enforced.
939
940
941.. decorator:: coroutine
942
943 Decorator to mark generator-based coroutines.
944
945 This decorator enables legacy generator-based coroutines to be
946 compatible with async/await code::
947
948 @asyncio.coroutine
949 def old_style_coroutine():
950 yield from asyncio.sleep(1)
951
952 async def main():
953 await old_style_coroutine()
954
Yury Selivanov3faaa882018-09-14 13:32:07 -0700955 This decorator should not be used for :keyword:`async def`
956 coroutines.
957
Andrew Svetlov68b34a72019-05-16 17:52:10 +0300958 .. deprecated-removed:: 3.8 3.10
959
960 Use :keyword:`async def` instead.
961
Yury Selivanov3faaa882018-09-14 13:32:07 -0700962.. function:: iscoroutine(obj)
963
964 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
965
966 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -0400967 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700968
969.. function:: iscoroutinefunction(func)
970
971 Return ``True`` if *func* is a :ref:`coroutine function
972 <coroutine>`.
973
974 This method is different from :func:`inspect.iscoroutinefunction`
975 because it returns ``True`` for generator-based coroutine functions
976 decorated with :func:`@coroutine <coroutine>`.