blob: 7efec5b6c1dfec0b197e66fc29794ec663320225 [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
215 This function runs the passed coroutine, taking care of
Yury Selivanov47150392018-09-18 17:55:44 -0400216 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 Selivanov3faaa882018-09-14 13:32:07 -0700222 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
229
230
Yury Selivanov3faaa882018-09-14 13:32:07 -0700231Creating Tasks
232==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100233
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300234.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200235
Yury Selivanove247b462018-09-20 12:43:59 -0400236 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
237 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300238
239 If *name* is not ``None``, it is set as the name of the task using
240 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200241
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400242 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200243 :exc:`RuntimeError` is raised if there is no running loop in
244 current thread.
245
Yury Selivanov47150392018-09-18 17:55:44 -0400246 This function has been **added in Python 3.7**. Prior to
247 Python 3.7, the low-level :func:`asyncio.ensure_future` function
248 can be used instead::
249
250 async def coro():
251 ...
252
253 # In Python 3.7+
254 task = asyncio.create_task(coro())
255 ...
256
257 # This works in all Python versions but is less readable
258 task = asyncio.ensure_future(coro())
259 ...
260
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200261 .. versionadded:: 3.7
262
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300263 .. versionchanged:: 3.8
264 Added the ``name`` parameter.
265
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
Yury Selivanov3faaa882018-09-14 13:32:07 -0700267Sleeping
268========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200269
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100270.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100271
Yury Selivanov3faaa882018-09-14 13:32:07 -0700272 Block for *delay* seconds.
273
274 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800275 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100276
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200277 ``sleep()`` always suspends the current task, allowing other tasks
278 to run.
279
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700280 .. deprecated-removed:: 3.8 3.10
281 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400282
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700283 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100284
Yury Selivanov3faaa882018-09-14 13:32:07 -0700285 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400286 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100287
Yury Selivanov3faaa882018-09-14 13:32:07 -0700288 import asyncio
289 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100290
Yury Selivanov3faaa882018-09-14 13:32:07 -0700291 async def display_date():
292 loop = asyncio.get_running_loop()
293 end_time = loop.time() + 5.0
294 while True:
295 print(datetime.datetime.now())
296 if (loop.time() + 1.0) >= end_time:
297 break
298 await asyncio.sleep(1)
299
300 asyncio.run(display_date())
301
302
303Running Tasks Concurrently
304==========================
305
Yury Selivanove247b462018-09-20 12:43:59 -0400306.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700307
Yury Selivanove247b462018-09-20 12:43:59 -0400308 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400309 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700310
Yury Selivanove247b462018-09-20 12:43:59 -0400311 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400312 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700313
Yury Selivanov47150392018-09-18 17:55:44 -0400314 If all awaitables are completed successfully, the result is an
315 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400316 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700317
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400318 If *return_exceptions* is ``False`` (default), the first
319 raised exception is immediately propagated to the task that
320 awaits on ``gather()``. Other awaitables in the *aws* sequence
321 **won't be cancelled** and will continue to run.
322
Yury Selivanov47150392018-09-18 17:55:44 -0400323 If *return_exceptions* is ``True``, exceptions are treated the
324 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700325
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400326 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700327 (that have not completed yet) are also *cancelled*.
328
Yury Selivanove247b462018-09-20 12:43:59 -0400329 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400330 treated as if it raised :exc:`CancelledError` -- the ``gather()``
331 call is **not** cancelled in this case. This is to prevent the
332 cancellation of one submitted Task/Future to cause other
333 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700334
Miss Islington (bot)345bfc92019-09-12 05:59:50 -0700335 .. deprecated-removed:: 3.8 3.10
336 The *loop* parameter.
337
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700338 .. _asyncio_example_gather:
339
Yury Selivanov3faaa882018-09-14 13:32:07 -0700340 Example::
341
342 import asyncio
343
344 async def factorial(name, number):
345 f = 1
346 for i in range(2, number + 1):
347 print(f"Task {name}: Compute factorial({i})...")
348 await asyncio.sleep(1)
349 f *= i
350 print(f"Task {name}: factorial({number}) = {f}")
351
352 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400353 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700354 await asyncio.gather(
355 factorial("A", 2),
356 factorial("B", 3),
357 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200358 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700359
360 asyncio.run(main())
361
362 # Expected output:
363 #
364 # Task A: Compute factorial(2)...
365 # Task B: Compute factorial(2)...
366 # Task C: Compute factorial(2)...
367 # Task A: factorial(2) = 2
368 # Task B: Compute factorial(3)...
369 # Task C: Compute factorial(3)...
370 # Task B: factorial(3) = 6
371 # Task C: Compute factorial(4)...
372 # Task C: factorial(4) = 24
373
Yury Selivanov47150392018-09-18 17:55:44 -0400374 .. versionchanged:: 3.7
375 If the *gather* itself is cancelled, the cancellation is
376 propagated regardless of *return_exceptions*.
377
Yury Selivanov3faaa882018-09-14 13:32:07 -0700378
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400379Shielding From Cancellation
380===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700381
Yury Selivanove247b462018-09-20 12:43:59 -0400382.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700383
Yury Selivanov47150392018-09-18 17:55:44 -0400384 Protect an :ref:`awaitable object <asyncio-awaitables>`
385 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700386
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400387 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388
389 The statement::
390
Andrew Svetlov88743422017-12-11 17:35:49 +0200391 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400393 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394
Andrew Svetlov88743422017-12-11 17:35:49 +0200395 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396
Yury Selivanov3faaa882018-09-14 13:32:07 -0700397 *except* that if the coroutine containing it is cancelled, the
398 Task running in ``something()`` is not cancelled. From the point
399 of view of ``something()``, the cancellation did not happen.
400 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400401 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402
Yury Selivanov3faaa882018-09-14 13:32:07 -0700403 If ``something()`` is cancelled by other means (i.e. from within
404 itself) that would also cancel ``shield()``.
405
406 If it is desired to completely ignore cancellation (not recommended)
407 the ``shield()`` function should be combined with a try/except
408 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100409
410 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200411 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412 except CancelledError:
413 res = None
414
Miss Islington (bot)345bfc92019-09-12 05:59:50 -0700415 .. deprecated-removed:: 3.8 3.10
416 The *loop* parameter.
417
Yury Selivanov950204d2016-05-16 16:23:00 -0400418
Yury Selivanov3faaa882018-09-14 13:32:07 -0700419Timeouts
420========
421
Yury Selivanove247b462018-09-20 12:43:59 -0400422.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700423
Yury Selivanove247b462018-09-20 12:43:59 -0400424 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400425 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700426
Yury Selivanove247b462018-09-20 12:43:59 -0400427 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700428
429 *timeout* can either be ``None`` or a float or int number of seconds
430 to wait for. If *timeout* is ``None``, block until the future
431 completes.
432
433 If a timeout occurs, it cancels the task and raises
434 :exc:`asyncio.TimeoutError`.
435
Yury Selivanov47150392018-09-18 17:55:44 -0400436 To avoid the task :meth:`cancellation <Task.cancel>`,
437 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700438
439 The function will wait until the future is actually cancelled,
440 so the total wait time may exceed the *timeout*.
441
Yury Selivanove247b462018-09-20 12:43:59 -0400442 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700443
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700444 .. deprecated-removed:: 3.8 3.10
445 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400446
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700447 .. _asyncio_example_waitfor:
448
Yury Selivanov3faaa882018-09-14 13:32:07 -0700449 Example::
450
451 async def eternity():
452 # Sleep for one hour
453 await asyncio.sleep(3600)
454 print('yay!')
455
456 async def main():
457 # Wait for at most 1 second
458 try:
459 await asyncio.wait_for(eternity(), timeout=1.0)
460 except asyncio.TimeoutError:
461 print('timeout!')
462
463 asyncio.run(main())
464
465 # Expected output:
466 #
467 # timeout!
468
469 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400470 When *aw* is cancelled due to a timeout, ``wait_for`` waits
471 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700472 :exc:`asyncio.TimeoutError` immediately.
473
474
475Waiting Primitives
476==================
477
Yury Selivanove247b462018-09-20 12:43:59 -0400478.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200479 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480
Yury Selivanove247b462018-09-20 12:43:59 -0400481 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov996859a2018-09-25 14:51:21 -0400482 set concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400483 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
Yury Selivanov3faaa882018-09-14 13:32:07 -0700485 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100486
Yury Selivanov996859a2018-09-25 14:51:21 -0400487 Usage::
488
489 done, pending = await asyncio.wait(aws)
490
Yury Selivanov3faaa882018-09-14 13:32:07 -0700491 *timeout* (a float or int), if specified, can be used to control
492 the maximum number of seconds to wait before returning.
493
494 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400495 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700496 returned in the second set.
497
498 *return_when* indicates when this function should return. It must
499 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100500
501 .. tabularcolumns:: |l|L|
502
503 +-----------------------------+----------------------------------------+
504 | Constant | Description |
505 +=============================+========================================+
506 | :const:`FIRST_COMPLETED` | The function will return when any |
507 | | future finishes or is cancelled. |
508 +-----------------------------+----------------------------------------+
509 | :const:`FIRST_EXCEPTION` | The function will return when any |
510 | | future finishes by raising an |
511 | | exception. If no future raises an |
512 | | exception then it is equivalent to |
513 | | :const:`ALL_COMPLETED`. |
514 +-----------------------------+----------------------------------------+
515 | :const:`ALL_COMPLETED` | The function will return when all |
516 | | futures finish or are cancelled. |
517 +-----------------------------+----------------------------------------+
518
Yury Selivanov3faaa882018-09-14 13:32:07 -0700519 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
520 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100521
Miss Islington (bot)345bfc92019-09-12 05:59:50 -0700522 .. deprecated:: 3.8
523
524 If any awaitable in *aws* is a coroutine, it is automatically
525 scheduled as a Task. Passing coroutines objects to
526 ``wait()`` directly is deprecated as it leads to
527 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
528
529 .. deprecated-removed:: 3.8 3.10
530
531 The *loop* parameter.
532
Yury Selivanov996859a2018-09-25 14:51:21 -0400533 .. _asyncio_example_wait_coroutine:
534 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100535
Yury Selivanov996859a2018-09-25 14:51:21 -0400536 ``wait()`` schedules coroutines as Tasks automatically and later
537 returns those implicitly created Task objects in ``(done, pending)``
538 sets. Therefore the following code won't work as expected::
539
540 async def foo():
541 return 42
542
543 coro = foo()
544 done, pending = await asyncio.wait({coro})
545
546 if coro in done:
547 # This branch will never be run!
548
549 Here is how the above snippet can be fixed::
550
551 async def foo():
552 return 42
553
554 task = asyncio.create_task(foo())
555 done, pending = await asyncio.wait({task})
556
557 if task in done:
558 # Everything will work as expected now.
559
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700560 .. deprecated:: 3.8
561
Yury Selivanov996859a2018-09-25 14:51:21 -0400562 Passing coroutine objects to ``wait()`` directly is
563 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100564
Victor Stinnerea3183f2013-12-03 01:08:00 +0100565
Yury Selivanove247b462018-09-20 12:43:59 -0400566.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700567
Yury Selivanove247b462018-09-20 12:43:59 -0400568 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400569 set concurrently. Return an iterator of :class:`Future` objects.
570 Each Future object returned represents the earliest result
571 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700572
573 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
574 all Futures are done.
575
Miss Islington (bot)345bfc92019-09-12 05:59:50 -0700576 .. deprecated-removed:: 3.8 3.10
577 The *loop* parameter.
578
Yury Selivanov3faaa882018-09-14 13:32:07 -0700579 Example::
580
Yury Selivanove247b462018-09-20 12:43:59 -0400581 for f in as_completed(aws):
Yury Selivanov47150392018-09-18 17:55:44 -0400582 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700583 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100584
Victor Stinner3e09e322013-12-03 01:22:06 +0100585
Yury Selivanov3faaa882018-09-14 13:32:07 -0700586Scheduling From Other Threads
587=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100588
Yury Selivanov3faaa882018-09-14 13:32:07 -0700589.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100590
Yury Selivanov3faaa882018-09-14 13:32:07 -0700591 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100592
Yury Selivanov47150392018-09-18 17:55:44 -0400593 Return a :class:`concurrent.futures.Future` to wait for the result
594 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100595
Yury Selivanov3faaa882018-09-14 13:32:07 -0700596 This function is meant to be called from a different OS thread
597 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200598
Yury Selivanov3faaa882018-09-14 13:32:07 -0700599 # Create a coroutine
600 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500601
Yury Selivanov3faaa882018-09-14 13:32:07 -0700602 # Submit the coroutine to a given loop
603 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100604
Yury Selivanov3faaa882018-09-14 13:32:07 -0700605 # Wait for the result with an optional timeout argument
606 assert future.result(timeout) == 3
607
608 If an exception is raised in the coroutine, the returned Future
609 will be notified. It can also be used to cancel the task in
610 the event loop::
611
612 try:
613 result = future.result(timeout)
614 except asyncio.TimeoutError:
615 print('The coroutine took too long, cancelling the task...')
616 future.cancel()
617 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700618 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700619 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700620 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700621
622 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
623 section of the documentation.
624
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530625 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700626 argument to be passed explicitly.
627
628 .. versionadded:: 3.5.1
629
630
631Introspection
632=============
633
634
635.. function:: current_task(loop=None)
636
637 Return the currently running :class:`Task` instance, or ``None`` if
638 no task is running.
639
640 If *loop* is ``None`` :func:`get_running_loop` is used to get
641 the current loop.
642
643 .. versionadded:: 3.7
644
645
646.. function:: all_tasks(loop=None)
647
648 Return a set of not yet finished :class:`Task` objects run by
649 the loop.
650
651 If *loop* is ``None``, :func:`get_running_loop` is used for getting
652 current loop.
653
654 .. versionadded:: 3.7
655
656
657Task Object
658===========
659
660.. class:: Task(coro, \*, loop=None, name=None)
661
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400662 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700663 :ref:`coroutine <coroutine>`. Not thread-safe.
664
665 Tasks are used to run coroutines in event loops.
666 If a coroutine awaits on a Future, the Task suspends
667 the execution of the coroutine and waits for the completion
668 of the Future. When the Future is *done*, the execution of
669 the wrapped coroutine resumes.
670
671 Event loops use cooperative scheduling: an event loop runs
672 one Task at a time. While a Task awaits for the completion of a
673 Future, the event loop runs other Tasks, callbacks, or performs
674 IO operations.
675
676 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400677 Tasks, or the low-level :meth:`loop.create_task` or
678 :func:`ensure_future` functions. Manual instantiation of Tasks
679 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700680
681 To cancel a running Task use the :meth:`cancel` method. Calling it
682 will cause the Task to throw a :exc:`CancelledError` exception into
683 the wrapped coroutine. If a coroutine is awaiting on a Future
684 object during cancellation, the Future object will be cancelled.
685
686 :meth:`cancelled` can be used to check if the Task was cancelled.
687 The method returns ``True`` if the wrapped coroutine did not
688 suppress the :exc:`CancelledError` exception and was actually
689 cancelled.
690
691 :class:`asyncio.Task` inherits from :class:`Future` all of its
692 APIs except :meth:`Future.set_result` and
693 :meth:`Future.set_exception`.
694
695 Tasks support the :mod:`contextvars` module. When a Task
696 is created it copies the current context and later runs its
697 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400698
699 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700700 Added support for the :mod:`contextvars` module.
701
702 .. versionchanged:: 3.8
703 Added the ``name`` parameter.
704
Miss Islington (bot)345bfc92019-09-12 05:59:50 -0700705 .. deprecated-removed:: 3.8 3.10
706 The *loop* parameter.
707
Yury Selivanov3faaa882018-09-14 13:32:07 -0700708 .. method:: cancel()
709
710 Request the Task to be cancelled.
711
712 This arranges for a :exc:`CancelledError` exception to be thrown
713 into the wrapped coroutine on the next cycle of the event loop.
714
715 The coroutine then has a chance to clean up or even deny the
716 request by suppressing the exception with a :keyword:`try` ...
717 ... ``except CancelledError`` ... :keyword:`finally` block.
718 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
719 not guarantee that the Task will be cancelled, although
720 suppressing cancellation completely is not common and is actively
721 discouraged.
722
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700723 .. _asyncio_example_task_cancel:
724
Yury Selivanov3faaa882018-09-14 13:32:07 -0700725 The following example illustrates how coroutines can intercept
726 the cancellation request::
727
728 async def cancel_me():
729 print('cancel_me(): before sleep')
730
731 try:
732 # Wait for 1 hour
733 await asyncio.sleep(3600)
734 except asyncio.CancelledError:
735 print('cancel_me(): cancel sleep')
736 raise
737 finally:
738 print('cancel_me(): after sleep')
739
740 async def main():
741 # Create a "cancel_me" Task
742 task = asyncio.create_task(cancel_me())
743
744 # Wait for 1 second
745 await asyncio.sleep(1)
746
747 task.cancel()
748 try:
749 await task
750 except asyncio.CancelledError:
751 print("main(): cancel_me is cancelled now")
752
753 asyncio.run(main())
754
755 # Expected output:
756 #
757 # cancel_me(): before sleep
758 # cancel_me(): cancel sleep
759 # cancel_me(): after sleep
760 # main(): cancel_me is cancelled now
761
762 .. method:: cancelled()
763
764 Return ``True`` if the Task is *cancelled*.
765
766 The Task is *cancelled* when the cancellation was requested with
767 :meth:`cancel` and the wrapped coroutine propagated the
768 :exc:`CancelledError` exception thrown into it.
769
770 .. method:: done()
771
772 Return ``True`` if the Task is *done*.
773
774 A Task is *done* when the wrapped coroutine either returned
775 a value, raised an exception, or the Task was cancelled.
776
Yury Selivanove247b462018-09-20 12:43:59 -0400777 .. method:: result()
778
779 Return the result of the Task.
780
781 If the Task is *done*, the result of the wrapped coroutine
782 is returned (or if the coroutine raised an exception, that
783 exception is re-raised.)
784
785 If the Task has been *cancelled*, this method raises
786 a :exc:`CancelledError` exception.
787
788 If the Task's result isn't yet available, this method raises
789 a :exc:`InvalidStateError` exception.
790
791 .. method:: exception()
792
793 Return the exception of the Task.
794
795 If the wrapped coroutine raised an exception that exception
796 is returned. If the wrapped coroutine returned normally
797 this method returns ``None``.
798
799 If the Task has been *cancelled*, this method raises a
800 :exc:`CancelledError` exception.
801
802 If the Task isn't *done* yet, this method raises an
803 :exc:`InvalidStateError` exception.
804
805 .. method:: add_done_callback(callback, *, context=None)
806
807 Add a callback to be run when the Task is *done*.
808
809 This method should only be used in low-level callback-based code.
810
811 See the documentation of :meth:`Future.add_done_callback`
812 for more details.
813
814 .. method:: remove_done_callback(callback)
815
816 Remove *callback* from the callbacks list.
817
818 This method should only be used in low-level callback-based code.
819
820 See the documentation of :meth:`Future.remove_done_callback`
821 for more details.
822
Yury Selivanov3faaa882018-09-14 13:32:07 -0700823 .. method:: get_stack(\*, limit=None)
824
825 Return the list of stack frames for this Task.
826
827 If the wrapped coroutine is not done, this returns the stack
828 where it is suspended. If the coroutine has completed
829 successfully or was cancelled, this returns an empty list.
830 If the coroutine was terminated by an exception, this returns
831 the list of traceback frames.
832
833 The frames are always ordered from oldest to newest.
834
835 Only one stack frame is returned for a suspended coroutine.
836
837 The optional *limit* argument sets the maximum number of frames
838 to return; by default all available frames are returned.
839 The ordering of the returned list differs depending on whether
840 a stack or a traceback is returned: the newest frames of a
841 stack are returned, but the oldest frames of a traceback are
842 returned. (This matches the behavior of the traceback module.)
843
844 .. method:: print_stack(\*, limit=None, file=None)
845
846 Print the stack or traceback for this Task.
847
848 This produces output similar to that of the traceback module
849 for the frames retrieved by :meth:`get_stack`.
850
851 The *limit* argument is passed to :meth:`get_stack` directly.
852
853 The *file* argument is an I/O stream to which the output
854 is written; by default output is written to :data:`sys.stderr`.
855
Alex Grönholm98ef9202019-05-30 18:30:09 +0300856 .. method:: get_coro()
857
858 Return the coroutine object wrapped by the :class:`Task`.
859
860 .. versionadded:: 3.8
861
Yury Selivanov3faaa882018-09-14 13:32:07 -0700862 .. method:: get_name()
863
864 Return the name of the Task.
865
866 If no name has been explicitly assigned to the Task, the default
867 asyncio Task implementation generates a default name during
868 instantiation.
869
870 .. versionadded:: 3.8
871
872 .. method:: set_name(value)
873
874 Set the name of the Task.
875
876 The *value* argument can be any object, which is then
877 converted to a string.
878
879 In the default Task implementation, the name will be visible
880 in the :func:`repr` output of a task object.
881
882 .. versionadded:: 3.8
883
884 .. classmethod:: all_tasks(loop=None)
885
886 Return a set of all tasks for an event loop.
887
888 By default all tasks for the current event loop are returned.
889 If *loop* is ``None``, the :func:`get_event_loop` function
890 is used to get the current loop.
891
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700892 .. deprecated-removed:: 3.7 3.9
893
894 Do not call this as a task method. Use the :func:`asyncio.all_tasks`
895 function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700896
897 .. classmethod:: current_task(loop=None)
898
899 Return the currently running task or ``None``.
900
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
907 :func:`asyncio.current_task` function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700908
909
910.. _asyncio_generator_based_coro:
911
912Generator-based Coroutines
913==========================
914
915.. note::
916
917 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -0400918 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700919
920Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400921Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700922on Futures and other coroutines.
923
924Generator-based coroutines should be decorated with
925:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
926enforced.
927
928
929.. decorator:: coroutine
930
931 Decorator to mark generator-based coroutines.
932
933 This decorator enables legacy generator-based coroutines to be
934 compatible with async/await code::
935
936 @asyncio.coroutine
937 def old_style_coroutine():
938 yield from asyncio.sleep(1)
939
940 async def main():
941 await old_style_coroutine()
942
Yury Selivanov3faaa882018-09-14 13:32:07 -0700943 This decorator should not be used for :keyword:`async def`
944 coroutines.
945
Andrew Svetlov68b34a72019-05-16 17:52:10 +0300946 .. deprecated-removed:: 3.8 3.10
947
948 Use :keyword:`async def` instead.
949
Yury Selivanov3faaa882018-09-14 13:32:07 -0700950.. function:: iscoroutine(obj)
951
952 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
953
954 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -0400955 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700956
957.. function:: iscoroutinefunction(func)
958
959 Return ``True`` if *func* is a :ref:`coroutine function
960 <coroutine>`.
961
962 This method is different from :func:`inspect.iscoroutinefunction`
963 because it returns ``True`` for generator-based coroutine functions
964 decorated with :func:`@coroutine <coroutine>`.