blob: d94fa587cd3a47315596234b9ae1583683cfa3d7 [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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -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 Selivanov3faaa882018-09-14 13:32:07 -0700233Creating Tasks
234==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300236.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200237
Yury Selivanove247b462018-09-20 12:43:59 -0400238 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
239 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300240
241 If *name* is not ``None``, it is set as the name of the task using
242 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200243
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400244 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200245 :exc:`RuntimeError` is raised if there is no running loop in
246 current thread.
247
Yury Selivanov47150392018-09-18 17:55:44 -0400248 This function has been **added in Python 3.7**. Prior to
249 Python 3.7, the low-level :func:`asyncio.ensure_future` function
250 can be used instead::
251
252 async def coro():
253 ...
254
255 # In Python 3.7+
256 task = asyncio.create_task(coro())
257 ...
258
259 # This works in all Python versions but is less readable
260 task = asyncio.ensure_future(coro())
261 ...
262
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200263 .. versionadded:: 3.7
264
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300265 .. versionchanged:: 3.8
266 Added the ``name`` parameter.
267
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
Yury Selivanov3faaa882018-09-14 13:32:07 -0700269Sleeping
270========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200271
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100272.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100273
Yury Selivanov3faaa882018-09-14 13:32:07 -0700274 Block for *delay* seconds.
275
276 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800277 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100278
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200279 ``sleep()`` always suspends the current task, allowing other tasks
280 to run.
281
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700282 .. deprecated-removed:: 3.8 3.10
283 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400284
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700285 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100286
Yury Selivanov3faaa882018-09-14 13:32:07 -0700287 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400288 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100289
Yury Selivanov3faaa882018-09-14 13:32:07 -0700290 import asyncio
291 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292
Yury Selivanov3faaa882018-09-14 13:32:07 -0700293 async def display_date():
294 loop = asyncio.get_running_loop()
295 end_time = loop.time() + 5.0
296 while True:
297 print(datetime.datetime.now())
298 if (loop.time() + 1.0) >= end_time:
299 break
300 await asyncio.sleep(1)
301
302 asyncio.run(display_date())
303
304
305Running Tasks Concurrently
306==========================
307
Yury Selivanove247b462018-09-20 12:43:59 -0400308.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700309
Yury Selivanove247b462018-09-20 12:43:59 -0400310 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400311 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700312
Yury Selivanove247b462018-09-20 12:43:59 -0400313 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400314 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700315
Yury Selivanov47150392018-09-18 17:55:44 -0400316 If all awaitables are completed successfully, the result is an
317 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400318 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700319
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400320 If *return_exceptions* is ``False`` (default), the first
321 raised exception is immediately propagated to the task that
322 awaits on ``gather()``. Other awaitables in the *aws* sequence
323 **won't be cancelled** and will continue to run.
324
Yury Selivanov47150392018-09-18 17:55:44 -0400325 If *return_exceptions* is ``True``, exceptions are treated the
326 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700327
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400328 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700329 (that have not completed yet) are also *cancelled*.
330
Yury Selivanove247b462018-09-20 12:43:59 -0400331 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400332 treated as if it raised :exc:`CancelledError` -- the ``gather()``
333 call is **not** cancelled in this case. This is to prevent the
334 cancellation of one submitted Task/Future to cause other
335 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700336
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700337 .. _asyncio_example_gather:
338
Yury Selivanov3faaa882018-09-14 13:32:07 -0700339 Example::
340
341 import asyncio
342
343 async def factorial(name, number):
344 f = 1
345 for i in range(2, number + 1):
346 print(f"Task {name}: Compute factorial({i})...")
347 await asyncio.sleep(1)
348 f *= i
349 print(f"Task {name}: factorial({number}) = {f}")
350
351 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400352 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700353 await asyncio.gather(
354 factorial("A", 2),
355 factorial("B", 3),
356 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200357 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700358
359 asyncio.run(main())
360
361 # Expected output:
362 #
363 # Task A: Compute factorial(2)...
364 # Task B: Compute factorial(2)...
365 # Task C: Compute factorial(2)...
366 # Task A: factorial(2) = 2
367 # Task B: Compute factorial(3)...
368 # Task C: Compute factorial(3)...
369 # Task B: factorial(3) = 6
370 # Task C: Compute factorial(4)...
371 # Task C: factorial(4) = 24
372
Yury Selivanov47150392018-09-18 17:55:44 -0400373 .. versionchanged:: 3.7
374 If the *gather* itself is cancelled, the cancellation is
375 propagated regardless of *return_exceptions*.
376
Yury Selivanov3faaa882018-09-14 13:32:07 -0700377
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400378Shielding From Cancellation
379===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700380
Yury Selivanove247b462018-09-20 12:43:59 -0400381.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700382
Yury Selivanov47150392018-09-18 17:55:44 -0400383 Protect an :ref:`awaitable object <asyncio-awaitables>`
384 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700385
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400386 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100387
388 The statement::
389
Andrew Svetlov88743422017-12-11 17:35:49 +0200390 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100391
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400392 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393
Andrew Svetlov88743422017-12-11 17:35:49 +0200394 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100395
Yury Selivanov3faaa882018-09-14 13:32:07 -0700396 *except* that if the coroutine containing it is cancelled, the
397 Task running in ``something()`` is not cancelled. From the point
398 of view of ``something()``, the cancellation did not happen.
399 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400400 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100401
Yury Selivanov3faaa882018-09-14 13:32:07 -0700402 If ``something()`` is cancelled by other means (i.e. from within
403 itself) that would also cancel ``shield()``.
404
405 If it is desired to completely ignore cancellation (not recommended)
406 the ``shield()`` function should be combined with a try/except
407 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100408
409 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200410 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411 except CancelledError:
412 res = None
413
Yury Selivanov950204d2016-05-16 16:23:00 -0400414
Yury Selivanov3faaa882018-09-14 13:32:07 -0700415Timeouts
416========
417
Yury Selivanove247b462018-09-20 12:43:59 -0400418.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700419
Yury Selivanove247b462018-09-20 12:43:59 -0400420 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400421 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700422
Yury Selivanove247b462018-09-20 12:43:59 -0400423 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700424
425 *timeout* can either be ``None`` or a float or int number of seconds
426 to wait for. If *timeout* is ``None``, block until the future
427 completes.
428
429 If a timeout occurs, it cancels the task and raises
430 :exc:`asyncio.TimeoutError`.
431
Yury Selivanov47150392018-09-18 17:55:44 -0400432 To avoid the task :meth:`cancellation <Task.cancel>`,
433 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700434
435 The function will wait until the future is actually cancelled,
436 so the total wait time may exceed the *timeout*.
437
Yury Selivanove247b462018-09-20 12:43:59 -0400438 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700439
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700440 .. deprecated-removed:: 3.8 3.10
441 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400442
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700443 .. _asyncio_example_waitfor:
444
Yury Selivanov3faaa882018-09-14 13:32:07 -0700445 Example::
446
447 async def eternity():
448 # Sleep for one hour
449 await asyncio.sleep(3600)
450 print('yay!')
451
452 async def main():
453 # Wait for at most 1 second
454 try:
455 await asyncio.wait_for(eternity(), timeout=1.0)
456 except asyncio.TimeoutError:
457 print('timeout!')
458
459 asyncio.run(main())
460
461 # Expected output:
462 #
463 # timeout!
464
465 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400466 When *aw* is cancelled due to a timeout, ``wait_for`` waits
467 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700468 :exc:`asyncio.TimeoutError` immediately.
469
470
471Waiting Primitives
472==================
473
Yury Selivanove247b462018-09-20 12:43:59 -0400474.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200475 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
Yury Selivanove247b462018-09-20 12:43:59 -0400477 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov996859a2018-09-25 14:51:21 -0400478 set concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400479 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700481 .. deprecated:: 3.8
482
483 If any awaitable in *aws* is a coroutine, it is automatically
484 scheduled as a Task. Passing coroutines objects to
485 ``wait()`` directly is deprecated as it leads to
486 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200487
Yury Selivanov3faaa882018-09-14 13:32:07 -0700488 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
Yury Selivanov996859a2018-09-25 14:51:21 -0400490 Usage::
491
492 done, pending = await asyncio.wait(aws)
493
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700494 .. deprecated-removed:: 3.8 3.10
495 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400496
Yury Selivanov3faaa882018-09-14 13:32:07 -0700497 *timeout* (a float or int), if specified, can be used to control
498 the maximum number of seconds to wait before returning.
499
500 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400501 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700502 returned in the second set.
503
504 *return_when* indicates when this function should return. It must
505 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506
507 .. tabularcolumns:: |l|L|
508
509 +-----------------------------+----------------------------------------+
510 | Constant | Description |
511 +=============================+========================================+
512 | :const:`FIRST_COMPLETED` | The function will return when any |
513 | | future finishes or is cancelled. |
514 +-----------------------------+----------------------------------------+
515 | :const:`FIRST_EXCEPTION` | The function will return when any |
516 | | future finishes by raising an |
517 | | exception. If no future raises an |
518 | | exception then it is equivalent to |
519 | | :const:`ALL_COMPLETED`. |
520 +-----------------------------+----------------------------------------+
521 | :const:`ALL_COMPLETED` | The function will return when all |
522 | | futures finish or are cancelled. |
523 +-----------------------------+----------------------------------------+
524
Yury Selivanov3faaa882018-09-14 13:32:07 -0700525 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
526 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanov996859a2018-09-25 14:51:21 -0400528 .. _asyncio_example_wait_coroutine:
529 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100530
Yury Selivanov996859a2018-09-25 14:51:21 -0400531 ``wait()`` schedules coroutines as Tasks automatically and later
532 returns those implicitly created Task objects in ``(done, pending)``
533 sets. Therefore the following code won't work as expected::
534
535 async def foo():
536 return 42
537
538 coro = foo()
539 done, pending = await asyncio.wait({coro})
540
541 if coro in done:
542 # This branch will never be run!
543
544 Here is how the above snippet can be fixed::
545
546 async def foo():
547 return 42
548
549 task = asyncio.create_task(foo())
550 done, pending = await asyncio.wait({task})
551
552 if task in done:
553 # Everything will work as expected now.
554
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700555 .. deprecated:: 3.8
556
Yury Selivanov996859a2018-09-25 14:51:21 -0400557 Passing coroutine objects to ``wait()`` directly is
558 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Victor Stinnerea3183f2013-12-03 01:08:00 +0100560
Yury Selivanove247b462018-09-20 12:43:59 -0400561.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700562
Yury Selivanove247b462018-09-20 12:43:59 -0400563 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400564 set concurrently. Return an iterator of :class:`Future` objects.
565 Each Future object returned represents the earliest result
566 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700567
568 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
569 all Futures are done.
570
571 Example::
572
Yury Selivanove247b462018-09-20 12:43:59 -0400573 for f in as_completed(aws):
Yury Selivanov47150392018-09-18 17:55:44 -0400574 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700575 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100576
Victor Stinner3e09e322013-12-03 01:22:06 +0100577
Yury Selivanov3faaa882018-09-14 13:32:07 -0700578Scheduling From Other Threads
579=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100580
Yury Selivanov3faaa882018-09-14 13:32:07 -0700581.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100582
Yury Selivanov3faaa882018-09-14 13:32:07 -0700583 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100584
Yury Selivanov47150392018-09-18 17:55:44 -0400585 Return a :class:`concurrent.futures.Future` to wait for the result
586 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100587
Yury Selivanov3faaa882018-09-14 13:32:07 -0700588 This function is meant to be called from a different OS thread
589 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200590
Yury Selivanov3faaa882018-09-14 13:32:07 -0700591 # Create a coroutine
592 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500593
Yury Selivanov3faaa882018-09-14 13:32:07 -0700594 # Submit the coroutine to a given loop
595 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100596
Yury Selivanov3faaa882018-09-14 13:32:07 -0700597 # Wait for the result with an optional timeout argument
598 assert future.result(timeout) == 3
599
600 If an exception is raised in the coroutine, the returned Future
601 will be notified. It can also be used to cancel the task in
602 the event loop::
603
604 try:
605 result = future.result(timeout)
606 except asyncio.TimeoutError:
607 print('The coroutine took too long, cancelling the task...')
608 future.cancel()
609 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700610 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700611 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700612 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700613
614 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
615 section of the documentation.
616
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530617 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700618 argument to be passed explicitly.
619
620 .. versionadded:: 3.5.1
621
622
623Introspection
624=============
625
626
627.. function:: current_task(loop=None)
628
629 Return the currently running :class:`Task` instance, or ``None`` if
630 no task is running.
631
632 If *loop* is ``None`` :func:`get_running_loop` is used to get
633 the current loop.
634
635 .. versionadded:: 3.7
636
637
638.. function:: all_tasks(loop=None)
639
640 Return a set of not yet finished :class:`Task` objects run by
641 the loop.
642
643 If *loop* is ``None``, :func:`get_running_loop` is used for getting
644 current loop.
645
646 .. versionadded:: 3.7
647
648
649Task Object
650===========
651
652.. class:: Task(coro, \*, loop=None, name=None)
653
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400654 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700655 :ref:`coroutine <coroutine>`. Not thread-safe.
656
657 Tasks are used to run coroutines in event loops.
658 If a coroutine awaits on a Future, the Task suspends
659 the execution of the coroutine and waits for the completion
660 of the Future. When the Future is *done*, the execution of
661 the wrapped coroutine resumes.
662
663 Event loops use cooperative scheduling: an event loop runs
664 one Task at a time. While a Task awaits for the completion of a
665 Future, the event loop runs other Tasks, callbacks, or performs
666 IO operations.
667
668 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400669 Tasks, or the low-level :meth:`loop.create_task` or
670 :func:`ensure_future` functions. Manual instantiation of Tasks
671 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700672
673 To cancel a running Task use the :meth:`cancel` method. Calling it
674 will cause the Task to throw a :exc:`CancelledError` exception into
675 the wrapped coroutine. If a coroutine is awaiting on a Future
676 object during cancellation, the Future object will be cancelled.
677
678 :meth:`cancelled` can be used to check if the Task was cancelled.
679 The method returns ``True`` if the wrapped coroutine did not
680 suppress the :exc:`CancelledError` exception and was actually
681 cancelled.
682
683 :class:`asyncio.Task` inherits from :class:`Future` all of its
684 APIs except :meth:`Future.set_result` and
685 :meth:`Future.set_exception`.
686
687 Tasks support the :mod:`contextvars` module. When a Task
688 is created it copies the current context and later runs its
689 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400690
691 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700692 Added support for the :mod:`contextvars` module.
693
694 .. versionchanged:: 3.8
695 Added the ``name`` parameter.
696
697 .. method:: cancel()
698
699 Request the Task to be cancelled.
700
701 This arranges for a :exc:`CancelledError` exception to be thrown
702 into the wrapped coroutine on the next cycle of the event loop.
703
704 The coroutine then has a chance to clean up or even deny the
705 request by suppressing the exception with a :keyword:`try` ...
706 ... ``except CancelledError`` ... :keyword:`finally` block.
707 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
708 not guarantee that the Task will be cancelled, although
709 suppressing cancellation completely is not common and is actively
710 discouraged.
711
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700712 .. _asyncio_example_task_cancel:
713
Yury Selivanov3faaa882018-09-14 13:32:07 -0700714 The following example illustrates how coroutines can intercept
715 the cancellation request::
716
717 async def cancel_me():
718 print('cancel_me(): before sleep')
719
720 try:
721 # Wait for 1 hour
722 await asyncio.sleep(3600)
723 except asyncio.CancelledError:
724 print('cancel_me(): cancel sleep')
725 raise
726 finally:
727 print('cancel_me(): after sleep')
728
729 async def main():
730 # Create a "cancel_me" Task
731 task = asyncio.create_task(cancel_me())
732
733 # Wait for 1 second
734 await asyncio.sleep(1)
735
736 task.cancel()
737 try:
738 await task
739 except asyncio.CancelledError:
740 print("main(): cancel_me is cancelled now")
741
742 asyncio.run(main())
743
744 # Expected output:
745 #
746 # cancel_me(): before sleep
747 # cancel_me(): cancel sleep
748 # cancel_me(): after sleep
749 # main(): cancel_me is cancelled now
750
751 .. method:: cancelled()
752
753 Return ``True`` if the Task is *cancelled*.
754
755 The Task is *cancelled* when the cancellation was requested with
756 :meth:`cancel` and the wrapped coroutine propagated the
757 :exc:`CancelledError` exception thrown into it.
758
759 .. method:: done()
760
761 Return ``True`` if the Task is *done*.
762
763 A Task is *done* when the wrapped coroutine either returned
764 a value, raised an exception, or the Task was cancelled.
765
Yury Selivanove247b462018-09-20 12:43:59 -0400766 .. method:: result()
767
768 Return the result of the Task.
769
770 If the Task is *done*, the result of the wrapped coroutine
771 is returned (or if the coroutine raised an exception, that
772 exception is re-raised.)
773
774 If the Task has been *cancelled*, this method raises
775 a :exc:`CancelledError` exception.
776
777 If the Task's result isn't yet available, this method raises
778 a :exc:`InvalidStateError` exception.
779
780 .. method:: exception()
781
782 Return the exception of the Task.
783
784 If the wrapped coroutine raised an exception that exception
785 is returned. If the wrapped coroutine returned normally
786 this method returns ``None``.
787
788 If the Task has been *cancelled*, this method raises a
789 :exc:`CancelledError` exception.
790
791 If the Task isn't *done* yet, this method raises an
792 :exc:`InvalidStateError` exception.
793
794 .. method:: add_done_callback(callback, *, context=None)
795
796 Add a callback to be run when the Task is *done*.
797
798 This method should only be used in low-level callback-based code.
799
800 See the documentation of :meth:`Future.add_done_callback`
801 for more details.
802
803 .. method:: remove_done_callback(callback)
804
805 Remove *callback* from the callbacks list.
806
807 This method should only be used in low-level callback-based code.
808
809 See the documentation of :meth:`Future.remove_done_callback`
810 for more details.
811
Yury Selivanov3faaa882018-09-14 13:32:07 -0700812 .. method:: get_stack(\*, limit=None)
813
814 Return the list of stack frames for this Task.
815
816 If the wrapped coroutine is not done, this returns the stack
817 where it is suspended. If the coroutine has completed
818 successfully or was cancelled, this returns an empty list.
819 If the coroutine was terminated by an exception, this returns
820 the list of traceback frames.
821
822 The frames are always ordered from oldest to newest.
823
824 Only one stack frame is returned for a suspended coroutine.
825
826 The optional *limit* argument sets the maximum number of frames
827 to return; by default all available frames are returned.
828 The ordering of the returned list differs depending on whether
829 a stack or a traceback is returned: the newest frames of a
830 stack are returned, but the oldest frames of a traceback are
831 returned. (This matches the behavior of the traceback module.)
832
833 .. method:: print_stack(\*, limit=None, file=None)
834
835 Print the stack or traceback for this Task.
836
837 This produces output similar to that of the traceback module
838 for the frames retrieved by :meth:`get_stack`.
839
840 The *limit* argument is passed to :meth:`get_stack` directly.
841
842 The *file* argument is an I/O stream to which the output
843 is written; by default output is written to :data:`sys.stderr`.
844
845 .. method:: get_name()
846
847 Return the name of the Task.
848
849 If no name has been explicitly assigned to the Task, the default
850 asyncio Task implementation generates a default name during
851 instantiation.
852
853 .. versionadded:: 3.8
854
855 .. method:: set_name(value)
856
857 Set the name of the Task.
858
859 The *value* argument can be any object, which is then
860 converted to a string.
861
862 In the default Task implementation, the name will be visible
863 in the :func:`repr` output of a task object.
864
865 .. versionadded:: 3.8
866
867 .. classmethod:: all_tasks(loop=None)
868
869 Return a set of all tasks for an event loop.
870
871 By default all tasks for the current event loop are returned.
872 If *loop* is ``None``, the :func:`get_event_loop` function
873 is used to get the current loop.
874
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700875 .. deprecated-removed:: 3.7 3.9
876
877 Do not call this as a task method. Use the :func:`asyncio.all_tasks`
878 function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700879
880 .. classmethod:: current_task(loop=None)
881
882 Return the currently running task or ``None``.
883
884 If *loop* is ``None``, the :func:`get_event_loop` function
885 is used to get the current loop.
886
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700887 .. deprecated-removed:: 3.7 3.9
888
889 Do not call this as a task method. Use the
890 :func:`asyncio.current_task` function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700891
892
893.. _asyncio_generator_based_coro:
894
895Generator-based Coroutines
896==========================
897
898.. note::
899
900 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -0400901 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700902
903Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400904Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700905on Futures and other coroutines.
906
907Generator-based coroutines should be decorated with
908:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
909enforced.
910
911
912.. decorator:: coroutine
913
914 Decorator to mark generator-based coroutines.
915
916 This decorator enables legacy generator-based coroutines to be
917 compatible with async/await code::
918
919 @asyncio.coroutine
920 def old_style_coroutine():
921 yield from asyncio.sleep(1)
922
923 async def main():
924 await old_style_coroutine()
925
Yury Selivanov3faaa882018-09-14 13:32:07 -0700926 This decorator should not be used for :keyword:`async def`
927 coroutines.
928
Andrew Svetlov68b34a72019-05-16 17:52:10 +0300929 .. deprecated-removed:: 3.8 3.10
930
931 Use :keyword:`async def` instead.
932
Yury Selivanov3faaa882018-09-14 13:32:07 -0700933.. function:: iscoroutine(obj)
934
935 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
936
937 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -0400938 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700939
940.. function:: iscoroutinefunction(func)
941
942 Return ``True`` if *func* is a :ref:`coroutine function
943 <coroutine>`.
944
945 This method is different from :func:`inspect.iscoroutinefunction`
946 because it returns ``True`` for generator-based coroutine functions
947 decorated with :func:`@coroutine <coroutine>`.