blob: d9320422db3b8b58bac40be4af7ec7fa00a35e74 [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
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400216 managing the asyncio event loop, *finalizing asynchronous
217 generators*, and closing the threadpool.
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
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400232 .. versionchanged:: 3.9
233 Updated to use :meth:`loop.shutdown_default_executor`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500234
Yury Selivanov3faaa882018-09-14 13:32:07 -0700235Creating Tasks
236==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300238.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200239
Yury Selivanove247b462018-09-20 12:43:59 -0400240 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
241 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300242
243 If *name* is not ``None``, it is set as the name of the task using
244 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200245
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400246 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200247 :exc:`RuntimeError` is raised if there is no running loop in
248 current thread.
249
Yury Selivanov47150392018-09-18 17:55:44 -0400250 This function has been **added in Python 3.7**. Prior to
251 Python 3.7, the low-level :func:`asyncio.ensure_future` function
252 can be used instead::
253
254 async def coro():
255 ...
256
257 # In Python 3.7+
258 task = asyncio.create_task(coro())
259 ...
260
261 # This works in all Python versions but is less readable
262 task = asyncio.ensure_future(coro())
263 ...
264
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200265 .. versionadded:: 3.7
266
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300267 .. versionchanged:: 3.8
268 Added the ``name`` parameter.
269
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270
Yury Selivanov3faaa882018-09-14 13:32:07 -0700271Sleeping
272========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200273
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100274.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100275
Yury Selivanov3faaa882018-09-14 13:32:07 -0700276 Block for *delay* seconds.
277
278 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800279 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200281 ``sleep()`` always suspends the current task, allowing other tasks
282 to run.
283
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700284 .. deprecated-removed:: 3.8 3.10
285 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400286
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700287 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100288
Yury Selivanov3faaa882018-09-14 13:32:07 -0700289 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400290 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100291
Yury Selivanov3faaa882018-09-14 13:32:07 -0700292 import asyncio
293 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100294
Yury Selivanov3faaa882018-09-14 13:32:07 -0700295 async def display_date():
296 loop = asyncio.get_running_loop()
297 end_time = loop.time() + 5.0
298 while True:
299 print(datetime.datetime.now())
300 if (loop.time() + 1.0) >= end_time:
301 break
302 await asyncio.sleep(1)
303
304 asyncio.run(display_date())
305
306
307Running Tasks Concurrently
308==========================
309
Yury Selivanove247b462018-09-20 12:43:59 -0400310.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700311
Yury Selivanove247b462018-09-20 12:43:59 -0400312 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400313 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700314
Yury Selivanove247b462018-09-20 12:43:59 -0400315 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400316 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700317
Yury Selivanov47150392018-09-18 17:55:44 -0400318 If all awaitables are completed successfully, the result is an
319 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400320 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700321
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400322 If *return_exceptions* is ``False`` (default), the first
323 raised exception is immediately propagated to the task that
324 awaits on ``gather()``. Other awaitables in the *aws* sequence
325 **won't be cancelled** and will continue to run.
326
Yury Selivanov47150392018-09-18 17:55:44 -0400327 If *return_exceptions* is ``True``, exceptions are treated the
328 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700329
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400330 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700331 (that have not completed yet) are also *cancelled*.
332
Yury Selivanove247b462018-09-20 12:43:59 -0400333 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400334 treated as if it raised :exc:`CancelledError` -- the ``gather()``
335 call is **not** cancelled in this case. This is to prevent the
336 cancellation of one submitted Task/Future to cause other
337 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700338
Andrew Svetlova4888792019-09-12 15:40:40 +0300339 .. deprecated-removed:: 3.8 3.10
340 The *loop* parameter.
341
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700342 .. _asyncio_example_gather:
343
Yury Selivanov3faaa882018-09-14 13:32:07 -0700344 Example::
345
346 import asyncio
347
348 async def factorial(name, number):
349 f = 1
350 for i in range(2, number + 1):
351 print(f"Task {name}: Compute factorial({i})...")
352 await asyncio.sleep(1)
353 f *= i
354 print(f"Task {name}: factorial({number}) = {f}")
355
356 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400357 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700358 await asyncio.gather(
359 factorial("A", 2),
360 factorial("B", 3),
361 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200362 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700363
364 asyncio.run(main())
365
366 # Expected output:
367 #
368 # Task A: Compute factorial(2)...
369 # Task B: Compute factorial(2)...
370 # Task C: Compute factorial(2)...
371 # Task A: factorial(2) = 2
372 # Task B: Compute factorial(3)...
373 # Task C: Compute factorial(3)...
374 # Task B: factorial(3) = 6
375 # Task C: Compute factorial(4)...
376 # Task C: factorial(4) = 24
377
Yury Selivanov47150392018-09-18 17:55:44 -0400378 .. versionchanged:: 3.7
379 If the *gather* itself is cancelled, the cancellation is
380 propagated regardless of *return_exceptions*.
381
Yury Selivanov3faaa882018-09-14 13:32:07 -0700382
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400383Shielding From Cancellation
384===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700385
Yury Selivanove247b462018-09-20 12:43:59 -0400386.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700387
Yury Selivanov47150392018-09-18 17:55:44 -0400388 Protect an :ref:`awaitable object <asyncio-awaitables>`
389 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700390
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400391 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
393 The statement::
394
Andrew Svetlov88743422017-12-11 17:35:49 +0200395 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400397 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100398
Andrew Svetlov88743422017-12-11 17:35:49 +0200399 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100400
Yury Selivanov3faaa882018-09-14 13:32:07 -0700401 *except* that if the coroutine containing it is cancelled, the
402 Task running in ``something()`` is not cancelled. From the point
403 of view of ``something()``, the cancellation did not happen.
404 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400405 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
Yury Selivanov3faaa882018-09-14 13:32:07 -0700407 If ``something()`` is cancelled by other means (i.e. from within
408 itself) that would also cancel ``shield()``.
409
410 If it is desired to completely ignore cancellation (not recommended)
411 the ``shield()`` function should be combined with a try/except
412 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100413
414 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200415 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100416 except CancelledError:
417 res = None
418
Andrew Svetlova4888792019-09-12 15:40:40 +0300419 .. deprecated-removed:: 3.8 3.10
420 The *loop* parameter.
421
Yury Selivanov950204d2016-05-16 16:23:00 -0400422
Yury Selivanov3faaa882018-09-14 13:32:07 -0700423Timeouts
424========
425
Yury Selivanove247b462018-09-20 12:43:59 -0400426.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700427
Yury Selivanove247b462018-09-20 12:43:59 -0400428 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400429 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700430
Yury Selivanove247b462018-09-20 12:43:59 -0400431 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700432
433 *timeout* can either be ``None`` or a float or int number of seconds
434 to wait for. If *timeout* is ``None``, block until the future
435 completes.
436
437 If a timeout occurs, it cancels the task and raises
438 :exc:`asyncio.TimeoutError`.
439
Yury Selivanov47150392018-09-18 17:55:44 -0400440 To avoid the task :meth:`cancellation <Task.cancel>`,
441 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700442
443 The function will wait until the future is actually cancelled,
444 so the total wait time may exceed the *timeout*.
445
Yury Selivanove247b462018-09-20 12:43:59 -0400446 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700447
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700448 .. deprecated-removed:: 3.8 3.10
449 The *loop* parameter.
Yury Selivanov47150392018-09-18 17:55:44 -0400450
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700451 .. _asyncio_example_waitfor:
452
Yury Selivanov3faaa882018-09-14 13:32:07 -0700453 Example::
454
455 async def eternity():
456 # Sleep for one hour
457 await asyncio.sleep(3600)
458 print('yay!')
459
460 async def main():
461 # Wait for at most 1 second
462 try:
463 await asyncio.wait_for(eternity(), timeout=1.0)
464 except asyncio.TimeoutError:
465 print('timeout!')
466
467 asyncio.run(main())
468
469 # Expected output:
470 #
471 # timeout!
472
473 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400474 When *aw* is cancelled due to a timeout, ``wait_for`` waits
475 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700476 :exc:`asyncio.TimeoutError` immediately.
477
478
479Waiting Primitives
480==================
481
Yury Selivanove247b462018-09-20 12:43:59 -0400482.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200483 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
Yury Selivanove247b462018-09-20 12:43:59 -0400485 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov996859a2018-09-25 14:51:21 -0400486 set concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400487 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100488
Yury Selivanov3faaa882018-09-14 13:32:07 -0700489 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100490
Yury Selivanov996859a2018-09-25 14:51:21 -0400491 Usage::
492
493 done, pending = await asyncio.wait(aws)
494
Yury Selivanov3faaa882018-09-14 13:32:07 -0700495 *timeout* (a float or int), if specified, can be used to control
496 the maximum number of seconds to wait before returning.
497
498 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400499 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700500 returned in the second set.
501
502 *return_when* indicates when this function should return. It must
503 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100504
505 .. tabularcolumns:: |l|L|
506
507 +-----------------------------+----------------------------------------+
508 | Constant | Description |
509 +=============================+========================================+
510 | :const:`FIRST_COMPLETED` | The function will return when any |
511 | | future finishes or is cancelled. |
512 +-----------------------------+----------------------------------------+
513 | :const:`FIRST_EXCEPTION` | The function will return when any |
514 | | future finishes by raising an |
515 | | exception. If no future raises an |
516 | | exception then it is equivalent to |
517 | | :const:`ALL_COMPLETED`. |
518 +-----------------------------+----------------------------------------+
519 | :const:`ALL_COMPLETED` | The function will return when all |
520 | | futures finish or are cancelled. |
521 +-----------------------------+----------------------------------------+
522
Yury Selivanov3faaa882018-09-14 13:32:07 -0700523 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
524 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100525
Andrew Svetlova4888792019-09-12 15:40:40 +0300526 .. deprecated:: 3.8
527
528 If any awaitable in *aws* is a coroutine, it is automatically
529 scheduled as a Task. Passing coroutines objects to
530 ``wait()`` directly is deprecated as it leads to
531 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
532
533 .. deprecated-removed:: 3.8 3.10
534
535 The *loop* parameter.
536
Yury Selivanov996859a2018-09-25 14:51:21 -0400537 .. _asyncio_example_wait_coroutine:
538 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100539
Yury Selivanov996859a2018-09-25 14:51:21 -0400540 ``wait()`` schedules coroutines as Tasks automatically and later
541 returns those implicitly created Task objects in ``(done, pending)``
542 sets. Therefore the following code won't work as expected::
543
544 async def foo():
545 return 42
546
547 coro = foo()
548 done, pending = await asyncio.wait({coro})
549
550 if coro in done:
551 # This branch will never be run!
552
553 Here is how the above snippet can be fixed::
554
555 async def foo():
556 return 42
557
558 task = asyncio.create_task(foo())
559 done, pending = await asyncio.wait({task})
560
561 if task in done:
562 # Everything will work as expected now.
563
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700564 .. deprecated:: 3.8
565
Yury Selivanov996859a2018-09-25 14:51:21 -0400566 Passing coroutine objects to ``wait()`` directly is
567 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100568
Victor Stinnerea3183f2013-12-03 01:08:00 +0100569
Yury Selivanove247b462018-09-20 12:43:59 -0400570.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700571
Yury Selivanove247b462018-09-20 12:43:59 -0400572 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400573 set concurrently. Return an iterator of :class:`Future` objects.
574 Each Future object returned represents the earliest result
575 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700576
577 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
578 all Futures are done.
579
Andrew Svetlova4888792019-09-12 15:40:40 +0300580 .. deprecated-removed:: 3.8 3.10
581 The *loop* parameter.
582
Yury Selivanov3faaa882018-09-14 13:32:07 -0700583 Example::
584
Yury Selivanove247b462018-09-20 12:43:59 -0400585 for f in as_completed(aws):
Yury Selivanov47150392018-09-18 17:55:44 -0400586 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700587 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100588
Victor Stinner3e09e322013-12-03 01:22:06 +0100589
Yury Selivanov3faaa882018-09-14 13:32:07 -0700590Scheduling From Other Threads
591=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100592
Yury Selivanov3faaa882018-09-14 13:32:07 -0700593.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100594
Yury Selivanov3faaa882018-09-14 13:32:07 -0700595 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100596
Yury Selivanov47150392018-09-18 17:55:44 -0400597 Return a :class:`concurrent.futures.Future` to wait for the result
598 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100599
Yury Selivanov3faaa882018-09-14 13:32:07 -0700600 This function is meant to be called from a different OS thread
601 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200602
Yury Selivanov3faaa882018-09-14 13:32:07 -0700603 # Create a coroutine
604 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500605
Yury Selivanov3faaa882018-09-14 13:32:07 -0700606 # Submit the coroutine to a given loop
607 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100608
Yury Selivanov3faaa882018-09-14 13:32:07 -0700609 # Wait for the result with an optional timeout argument
610 assert future.result(timeout) == 3
611
612 If an exception is raised in the coroutine, the returned Future
613 will be notified. It can also be used to cancel the task in
614 the event loop::
615
616 try:
617 result = future.result(timeout)
618 except asyncio.TimeoutError:
619 print('The coroutine took too long, cancelling the task...')
620 future.cancel()
621 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700622 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700623 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700624 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700625
626 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
627 section of the documentation.
628
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530629 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700630 argument to be passed explicitly.
631
632 .. versionadded:: 3.5.1
633
634
635Introspection
636=============
637
638
639.. function:: current_task(loop=None)
640
641 Return the currently running :class:`Task` instance, or ``None`` if
642 no task is running.
643
644 If *loop* is ``None`` :func:`get_running_loop` is used to get
645 the current loop.
646
647 .. versionadded:: 3.7
648
649
650.. function:: all_tasks(loop=None)
651
652 Return a set of not yet finished :class:`Task` objects run by
653 the loop.
654
655 If *loop* is ``None``, :func:`get_running_loop` is used for getting
656 current loop.
657
658 .. versionadded:: 3.7
659
660
661Task Object
662===========
663
664.. class:: Task(coro, \*, loop=None, name=None)
665
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400666 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700667 :ref:`coroutine <coroutine>`. Not thread-safe.
668
669 Tasks are used to run coroutines in event loops.
670 If a coroutine awaits on a Future, the Task suspends
671 the execution of the coroutine and waits for the completion
672 of the Future. When the Future is *done*, the execution of
673 the wrapped coroutine resumes.
674
675 Event loops use cooperative scheduling: an event loop runs
676 one Task at a time. While a Task awaits for the completion of a
677 Future, the event loop runs other Tasks, callbacks, or performs
678 IO operations.
679
680 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400681 Tasks, or the low-level :meth:`loop.create_task` or
682 :func:`ensure_future` functions. Manual instantiation of Tasks
683 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700684
685 To cancel a running Task use the :meth:`cancel` method. Calling it
686 will cause the Task to throw a :exc:`CancelledError` exception into
687 the wrapped coroutine. If a coroutine is awaiting on a Future
688 object during cancellation, the Future object will be cancelled.
689
690 :meth:`cancelled` can be used to check if the Task was cancelled.
691 The method returns ``True`` if the wrapped coroutine did not
692 suppress the :exc:`CancelledError` exception and was actually
693 cancelled.
694
695 :class:`asyncio.Task` inherits from :class:`Future` all of its
696 APIs except :meth:`Future.set_result` and
697 :meth:`Future.set_exception`.
698
699 Tasks support the :mod:`contextvars` module. When a Task
700 is created it copies the current context and later runs its
701 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400702
703 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700704 Added support for the :mod:`contextvars` module.
705
706 .. versionchanged:: 3.8
707 Added the ``name`` parameter.
708
Andrew Svetlova4888792019-09-12 15:40:40 +0300709 .. deprecated-removed:: 3.8 3.10
710 The *loop* parameter.
711
Yury Selivanov3faaa882018-09-14 13:32:07 -0700712 .. method:: cancel()
713
714 Request the Task to be cancelled.
715
716 This arranges for a :exc:`CancelledError` exception to be thrown
717 into the wrapped coroutine on the next cycle of the event loop.
718
719 The coroutine then has a chance to clean up or even deny the
720 request by suppressing the exception with a :keyword:`try` ...
721 ... ``except CancelledError`` ... :keyword:`finally` block.
722 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
723 not guarantee that the Task will be cancelled, although
724 suppressing cancellation completely is not common and is actively
725 discouraged.
726
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700727 .. _asyncio_example_task_cancel:
728
Yury Selivanov3faaa882018-09-14 13:32:07 -0700729 The following example illustrates how coroutines can intercept
730 the cancellation request::
731
732 async def cancel_me():
733 print('cancel_me(): before sleep')
734
735 try:
736 # Wait for 1 hour
737 await asyncio.sleep(3600)
738 except asyncio.CancelledError:
739 print('cancel_me(): cancel sleep')
740 raise
741 finally:
742 print('cancel_me(): after sleep')
743
744 async def main():
745 # Create a "cancel_me" Task
746 task = asyncio.create_task(cancel_me())
747
748 # Wait for 1 second
749 await asyncio.sleep(1)
750
751 task.cancel()
752 try:
753 await task
754 except asyncio.CancelledError:
755 print("main(): cancel_me is cancelled now")
756
757 asyncio.run(main())
758
759 # Expected output:
760 #
761 # cancel_me(): before sleep
762 # cancel_me(): cancel sleep
763 # cancel_me(): after sleep
764 # main(): cancel_me is cancelled now
765
766 .. method:: cancelled()
767
768 Return ``True`` if the Task is *cancelled*.
769
770 The Task is *cancelled* when the cancellation was requested with
771 :meth:`cancel` and the wrapped coroutine propagated the
772 :exc:`CancelledError` exception thrown into it.
773
774 .. method:: done()
775
776 Return ``True`` if the Task is *done*.
777
778 A Task is *done* when the wrapped coroutine either returned
779 a value, raised an exception, or the Task was cancelled.
780
Yury Selivanove247b462018-09-20 12:43:59 -0400781 .. method:: result()
782
783 Return the result of the Task.
784
785 If the Task is *done*, the result of the wrapped coroutine
786 is returned (or if the coroutine raised an exception, that
787 exception is re-raised.)
788
789 If the Task has been *cancelled*, this method raises
790 a :exc:`CancelledError` exception.
791
792 If the Task's result isn't yet available, this method raises
793 a :exc:`InvalidStateError` exception.
794
795 .. method:: exception()
796
797 Return the exception of the Task.
798
799 If the wrapped coroutine raised an exception that exception
800 is returned. If the wrapped coroutine returned normally
801 this method returns ``None``.
802
803 If the Task has been *cancelled*, this method raises a
804 :exc:`CancelledError` exception.
805
806 If the Task isn't *done* yet, this method raises an
807 :exc:`InvalidStateError` exception.
808
809 .. method:: add_done_callback(callback, *, context=None)
810
811 Add a callback to be run when the Task is *done*.
812
813 This method should only be used in low-level callback-based code.
814
815 See the documentation of :meth:`Future.add_done_callback`
816 for more details.
817
818 .. method:: remove_done_callback(callback)
819
820 Remove *callback* from the callbacks list.
821
822 This method should only be used in low-level callback-based code.
823
824 See the documentation of :meth:`Future.remove_done_callback`
825 for more details.
826
Yury Selivanov3faaa882018-09-14 13:32:07 -0700827 .. method:: get_stack(\*, limit=None)
828
829 Return the list of stack frames for this Task.
830
831 If the wrapped coroutine is not done, this returns the stack
832 where it is suspended. If the coroutine has completed
833 successfully or was cancelled, this returns an empty list.
834 If the coroutine was terminated by an exception, this returns
835 the list of traceback frames.
836
837 The frames are always ordered from oldest to newest.
838
839 Only one stack frame is returned for a suspended coroutine.
840
841 The optional *limit* argument sets the maximum number of frames
842 to return; by default all available frames are returned.
843 The ordering of the returned list differs depending on whether
844 a stack or a traceback is returned: the newest frames of a
845 stack are returned, but the oldest frames of a traceback are
846 returned. (This matches the behavior of the traceback module.)
847
848 .. method:: print_stack(\*, limit=None, file=None)
849
850 Print the stack or traceback for this Task.
851
852 This produces output similar to that of the traceback module
853 for the frames retrieved by :meth:`get_stack`.
854
855 The *limit* argument is passed to :meth:`get_stack` directly.
856
857 The *file* argument is an I/O stream to which the output
858 is written; by default output is written to :data:`sys.stderr`.
859
Alex Grönholm98ef9202019-05-30 18:30:09 +0300860 .. method:: get_coro()
861
862 Return the coroutine object wrapped by the :class:`Task`.
863
864 .. versionadded:: 3.8
865
Yury Selivanov3faaa882018-09-14 13:32:07 -0700866 .. method:: get_name()
867
868 Return the name of the Task.
869
870 If no name has been explicitly assigned to the Task, the default
871 asyncio Task implementation generates a default name during
872 instantiation.
873
874 .. versionadded:: 3.8
875
876 .. method:: set_name(value)
877
878 Set the name of the Task.
879
880 The *value* argument can be any object, which is then
881 converted to a string.
882
883 In the default Task implementation, the name will be visible
884 in the :func:`repr` output of a task object.
885
886 .. versionadded:: 3.8
887
888 .. classmethod:: all_tasks(loop=None)
889
890 Return a set of all tasks for an event loop.
891
892 By default all tasks for the current event loop are returned.
893 If *loop* is ``None``, the :func:`get_event_loop` function
894 is used to get the current loop.
895
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700896 .. deprecated-removed:: 3.7 3.9
897
898 Do not call this as a task method. Use the :func:`asyncio.all_tasks`
899 function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700900
901 .. classmethod:: current_task(loop=None)
902
903 Return the currently running task or ``None``.
904
905 If *loop* is ``None``, the :func:`get_event_loop` function
906 is used to get the current loop.
907
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700908 .. deprecated-removed:: 3.7 3.9
909
910 Do not call this as a task method. Use the
911 :func:`asyncio.current_task` function instead.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700912
913
914.. _asyncio_generator_based_coro:
915
916Generator-based Coroutines
917==========================
918
919.. note::
920
921 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -0400922 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700923
924Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400925Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700926on Futures and other coroutines.
927
928Generator-based coroutines should be decorated with
929:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
930enforced.
931
932
933.. decorator:: coroutine
934
935 Decorator to mark generator-based coroutines.
936
937 This decorator enables legacy generator-based coroutines to be
938 compatible with async/await code::
939
940 @asyncio.coroutine
941 def old_style_coroutine():
942 yield from asyncio.sleep(1)
943
944 async def main():
945 await old_style_coroutine()
946
Yury Selivanov3faaa882018-09-14 13:32:07 -0700947 This decorator should not be used for :keyword:`async def`
948 coroutines.
949
Andrew Svetlov68b34a72019-05-16 17:52:10 +0300950 .. deprecated-removed:: 3.8 3.10
951
952 Use :keyword:`async def` instead.
953
Yury Selivanov3faaa882018-09-14 13:32:07 -0700954.. function:: iscoroutine(obj)
955
956 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
957
958 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -0400959 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700960
961.. function:: iscoroutinefunction(func)
962
963 Return ``True`` if *func* is a :ref:`coroutine function
964 <coroutine>`.
965
966 This method is different from :func:`inspect.iscoroutinefunction`
967 because it returns ``True`` for generator-based coroutine functions
968 decorated with :func:`@coroutine <coroutine>`.