blob: bbdef3345a4d42f87691c56d69f31ec402ebc9d3 [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
Kyle Stanleyf9000642019-10-10 19:18:46 -040021:term:`Coroutines <coroutine>` declared with the async/await syntax is the
22preferred way of writing asyncio applications. For example, the following
23snippet of code (requires Python 3.7+) prints "hello", waits 1 second,
Yury Selivanovb042cf12018-09-18 02:47:54 -040024and 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
Andre Delfinodcc997c2020-12-16 22:37:28 -0300213.. function:: run(coro, *, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500214
Kyle Stanleye4070132019-09-30 20:12:21 -0400215 Execute the :term:`coroutine` *coro* and return the result.
216
Yury Selivanov02a0a192017-12-14 09:42:21 -0500217 This function runs the passed coroutine, taking care of
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400218 managing the asyncio event loop, *finalizing asynchronous
219 generators*, and closing the threadpool.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500220
221 This function cannot be called when another asyncio event loop is
222 running in the same thread.
223
Yury Selivanov3faaa882018-09-14 13:32:07 -0700224 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500225
226 This function always creates a new event loop and closes it at
227 the end. It should be used as a main entry point for asyncio
228 programs, and should ideally only be called once.
229
Emmanuel Arias17deb162019-09-25 05:53:49 -0300230 Example::
231
232 async def main():
233 await asyncio.sleep(1)
234 print('hello')
235
236 asyncio.run(main())
237
Yury Selivanov02a0a192017-12-14 09:42:21 -0500238 .. versionadded:: 3.7
239
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400240 .. versionchanged:: 3.9
241 Updated to use :meth:`loop.shutdown_default_executor`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500242
Kyle Stanleyf9000642019-10-10 19:18:46 -0400243 .. note::
244 The source code for ``asyncio.run()`` can be found in
245 :source:`Lib/asyncio/runners.py`.
246
Yury Selivanov3faaa882018-09-14 13:32:07 -0700247Creating Tasks
248==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100249
Andre Delfinodcc997c2020-12-16 22:37:28 -0300250.. function:: create_task(coro, *, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200251
Yury Selivanove247b462018-09-20 12:43:59 -0400252 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
253 and schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300254
255 If *name* is not ``None``, it is set as the name of the task using
256 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200257
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400258 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200259 :exc:`RuntimeError` is raised if there is no running loop in
260 current thread.
261
Yury Selivanov47150392018-09-18 17:55:44 -0400262 This function has been **added in Python 3.7**. Prior to
263 Python 3.7, the low-level :func:`asyncio.ensure_future` function
264 can be used instead::
265
266 async def coro():
267 ...
268
269 # In Python 3.7+
270 task = asyncio.create_task(coro())
271 ...
272
273 # This works in all Python versions but is less readable
274 task = asyncio.ensure_future(coro())
275 ...
276
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200277 .. versionadded:: 3.7
278
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300279 .. versionchanged:: 3.8
280 Added the ``name`` parameter.
281
Victor Stinnerea3183f2013-12-03 01:08:00 +0100282
Yury Selivanov3faaa882018-09-14 13:32:07 -0700283Sleeping
284========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200285
Yurii Karabas86150d32020-11-29 14:50:57 +0200286.. coroutinefunction:: sleep(delay, result=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
Yury Selivanov3faaa882018-09-14 13:32:07 -0700288 Block for *delay* seconds.
289
290 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800291 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292
Hrvoje Nikšićcd602b82018-10-01 12:09:38 +0200293 ``sleep()`` always suspends the current task, allowing other tasks
294 to run.
295
Simon Willison5c301452021-01-06 18:03:18 -0800296 Setting the delay to 0 provides an optimized path to allow other
297 tasks to run. This can be used by long-running functions to avoid
298 blocking the event loop for the full duration of the function call.
299
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700300 .. deprecated-removed:: 3.8 3.10
301 The ``loop`` parameter. This function has been implicitly getting the
302 current running loop since 3.7. See
303 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
304 for more information.
305
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700306 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100307
Yury Selivanov3faaa882018-09-14 13:32:07 -0700308 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400309 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100310
Yury Selivanov3faaa882018-09-14 13:32:07 -0700311 import asyncio
312 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100313
Yury Selivanov3faaa882018-09-14 13:32:07 -0700314 async def display_date():
315 loop = asyncio.get_running_loop()
316 end_time = loop.time() + 5.0
317 while True:
318 print(datetime.datetime.now())
319 if (loop.time() + 1.0) >= end_time:
320 break
321 await asyncio.sleep(1)
322
323 asyncio.run(display_date())
324
325
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700326 .. deprecated-removed:: 3.8 3.10
327
328 The ``loop`` parameter. This function has been implicitly getting the
329 current running loop since 3.7. See
330 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
331 for more information.
332
333
Yury Selivanov3faaa882018-09-14 13:32:07 -0700334Running Tasks Concurrently
335==========================
336
Andre Delfinodcc997c2020-12-16 22:37:28 -0300337.. awaitablefunction:: gather(*aws, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700338
Yury Selivanove247b462018-09-20 12:43:59 -0400339 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Yury Selivanov47150392018-09-18 17:55:44 -0400340 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700341
Yury Selivanove247b462018-09-20 12:43:59 -0400342 If any awaitable in *aws* is a coroutine, it is automatically
Yury Selivanov47150392018-09-18 17:55:44 -0400343 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700344
Yury Selivanov47150392018-09-18 17:55:44 -0400345 If all awaitables are completed successfully, the result is an
346 aggregate list of returned values. The order of result values
Yury Selivanove247b462018-09-20 12:43:59 -0400347 corresponds to the order of awaitables in *aws*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700348
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400349 If *return_exceptions* is ``False`` (default), the first
350 raised exception is immediately propagated to the task that
351 awaits on ``gather()``. Other awaitables in the *aws* sequence
352 **won't be cancelled** and will continue to run.
353
Yury Selivanov47150392018-09-18 17:55:44 -0400354 If *return_exceptions* is ``True``, exceptions are treated the
355 same as successful results, and aggregated in the result list.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700356
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400357 If ``gather()`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700358 (that have not completed yet) are also *cancelled*.
359
Yury Selivanove247b462018-09-20 12:43:59 -0400360 If any Task or Future from the *aws* sequence is *cancelled*, it is
Yury Selivanov47150392018-09-18 17:55:44 -0400361 treated as if it raised :exc:`CancelledError` -- the ``gather()``
362 call is **not** cancelled in this case. This is to prevent the
363 cancellation of one submitted Task/Future to cause other
364 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700365
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700366 .. deprecated-removed:: 3.8 3.10
367 The ``loop`` parameter. This function has been implicitly getting the
368 current running loop since 3.7. See
369 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
370 for more information.
371
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700372 .. _asyncio_example_gather:
373
Yury Selivanov3faaa882018-09-14 13:32:07 -0700374 Example::
375
376 import asyncio
377
378 async def factorial(name, number):
379 f = 1
380 for i in range(2, number + 1):
Miss Islington (bot)46426972021-05-13 23:07:20 -0700381 print(f"Task {name}: Compute factorial({number}), currently i={i}...")
Yury Selivanov3faaa882018-09-14 13:32:07 -0700382 await asyncio.sleep(1)
383 f *= i
384 print(f"Task {name}: factorial({number}) = {f}")
Miss Islington (bot)46426972021-05-13 23:07:20 -0700385 return f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700386
387 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400388 # Schedule three calls *concurrently*:
Miss Islington (bot)46426972021-05-13 23:07:20 -0700389 L = await asyncio.gather(
Yury Selivanov3faaa882018-09-14 13:32:07 -0700390 factorial("A", 2),
391 factorial("B", 3),
392 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200393 )
Miss Islington (bot)46426972021-05-13 23:07:20 -0700394 print(L)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700395
396 asyncio.run(main())
397
398 # Expected output:
399 #
Miss Islington (bot)46426972021-05-13 23:07:20 -0700400 # Task A: Compute factorial(2), currently i=2...
401 # Task B: Compute factorial(3), currently i=2...
402 # Task C: Compute factorial(4), currently i=2...
Yury Selivanov3faaa882018-09-14 13:32:07 -0700403 # Task A: factorial(2) = 2
Miss Islington (bot)46426972021-05-13 23:07:20 -0700404 # Task B: Compute factorial(3), currently i=3...
405 # Task C: Compute factorial(4), currently i=3...
Yury Selivanov3faaa882018-09-14 13:32:07 -0700406 # Task B: factorial(3) = 6
Miss Islington (bot)46426972021-05-13 23:07:20 -0700407 # Task C: Compute factorial(4), currently i=4...
Yury Selivanov3faaa882018-09-14 13:32:07 -0700408 # Task C: factorial(4) = 24
Miss Islington (bot)46426972021-05-13 23:07:20 -0700409 # [2, 6, 24]
Yury Selivanov3faaa882018-09-14 13:32:07 -0700410
Vinay Sharmad42528a2020-07-20 14:12:57 +0530411 .. note::
412 If *return_exceptions* is False, cancelling gather() after it
413 has been marked done won't cancel any submitted awaitables.
414 For instance, gather can be marked done after propagating an
415 exception to the caller, therefore, calling ``gather.cancel()``
416 after catching an exception (raised by one of the awaitables) from
417 gather won't cancel any other awaitables.
418
Yury Selivanov47150392018-09-18 17:55:44 -0400419 .. versionchanged:: 3.7
420 If the *gather* itself is cancelled, the cancellation is
421 propagated regardless of *return_exceptions*.
422
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700423 .. deprecated-removed:: 3.8 3.10
424 The ``loop`` parameter. This function has been implicitly getting the
425 current running loop since 3.7. See
426 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
427 for more information.
428
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300429 .. deprecated:: 3.10
430 Deprecation warning is emitted if no positional arguments are provided
431 or not all positional arguments are Future-like objects
432 and there is no running event loop.
433
Yury Selivanov3faaa882018-09-14 13:32:07 -0700434
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400435Shielding From Cancellation
436===========================
Yury Selivanov3faaa882018-09-14 13:32:07 -0700437
Yurii Karabas86150d32020-11-29 14:50:57 +0200438.. awaitablefunction:: shield(aw)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700439
Yury Selivanov47150392018-09-18 17:55:44 -0400440 Protect an :ref:`awaitable object <asyncio-awaitables>`
441 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700442
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400443 If *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100444
445 The statement::
446
Andrew Svetlov88743422017-12-11 17:35:49 +0200447 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100448
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400449 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
Andrew Svetlov88743422017-12-11 17:35:49 +0200451 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Yury Selivanov3faaa882018-09-14 13:32:07 -0700453 *except* that if the coroutine containing it is cancelled, the
454 Task running in ``something()`` is not cancelled. From the point
455 of view of ``something()``, the cancellation did not happen.
456 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400457 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100458
Yury Selivanov3faaa882018-09-14 13:32:07 -0700459 If ``something()`` is cancelled by other means (i.e. from within
460 itself) that would also cancel ``shield()``.
461
462 If it is desired to completely ignore cancellation (not recommended)
463 the ``shield()`` function should be combined with a try/except
464 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100465
466 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200467 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100468 except CancelledError:
469 res = None
470
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700471 .. deprecated-removed:: 3.8 3.10
472 The ``loop`` parameter. This function has been implicitly getting the
473 current running loop since 3.7. See
474 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
475 for more information.
476
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300477 .. deprecated:: 3.10
478 Deprecation warning is emitted if *aw* is not Future-like object
479 and there is no running event loop.
480
Yury Selivanov950204d2016-05-16 16:23:00 -0400481
Yury Selivanov3faaa882018-09-14 13:32:07 -0700482Timeouts
483========
484
Yurii Karabas86150d32020-11-29 14:50:57 +0200485.. coroutinefunction:: wait_for(aw, timeout)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700486
Yury Selivanove247b462018-09-20 12:43:59 -0400487 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Yury Selivanov47150392018-09-18 17:55:44 -0400488 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700489
Yury Selivanove247b462018-09-20 12:43:59 -0400490 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700491
492 *timeout* can either be ``None`` or a float or int number of seconds
493 to wait for. If *timeout* is ``None``, block until the future
494 completes.
495
496 If a timeout occurs, it cancels the task and raises
497 :exc:`asyncio.TimeoutError`.
498
Yury Selivanov47150392018-09-18 17:55:44 -0400499 To avoid the task :meth:`cancellation <Task.cancel>`,
500 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700501
502 The function will wait until the future is actually cancelled,
romasku382a5632020-05-15 23:12:05 +0300503 so the total wait time may exceed the *timeout*. If an exception
504 happens during cancellation, it is propagated.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700505
Yury Selivanove247b462018-09-20 12:43:59 -0400506 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700507
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700508 .. deprecated-removed:: 3.8 3.10
509 The ``loop`` parameter. This function has been implicitly getting the
510 current running loop since 3.7. See
511 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
512 for more information.
513
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700514 .. _asyncio_example_waitfor:
515
Yury Selivanov3faaa882018-09-14 13:32:07 -0700516 Example::
517
518 async def eternity():
519 # Sleep for one hour
520 await asyncio.sleep(3600)
521 print('yay!')
522
523 async def main():
524 # Wait for at most 1 second
525 try:
526 await asyncio.wait_for(eternity(), timeout=1.0)
527 except asyncio.TimeoutError:
528 print('timeout!')
529
530 asyncio.run(main())
531
532 # Expected output:
533 #
534 # timeout!
535
536 .. versionchanged:: 3.7
Yury Selivanove247b462018-09-20 12:43:59 -0400537 When *aw* is cancelled due to a timeout, ``wait_for`` waits
538 for *aw* to be cancelled. Previously, it raised
Yury Selivanov3faaa882018-09-14 13:32:07 -0700539 :exc:`asyncio.TimeoutError` immediately.
540
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700541 .. deprecated-removed:: 3.8 3.10
542 The ``loop`` parameter. This function has been implicitly getting the
543 current running loop since 3.7. See
544 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
545 for more information.
546
Yury Selivanov3faaa882018-09-14 13:32:07 -0700547
548Waiting Primitives
549==================
550
Andre Delfinodcc997c2020-12-16 22:37:28 -0300551.. coroutinefunction:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100552
Yury Selivanove247b462018-09-20 12:43:59 -0400553 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100554 iterable concurrently and block until the condition specified
Yury Selivanov47150392018-09-18 17:55:44 -0400555 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100556
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100557 The *aws* iterable must not be empty.
Joel Rosdahl9d746582020-05-04 23:56:00 +0200558
Yury Selivanov3faaa882018-09-14 13:32:07 -0700559 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100560
Yury Selivanov996859a2018-09-25 14:51:21 -0400561 Usage::
562
563 done, pending = await asyncio.wait(aws)
564
Yury Selivanov3faaa882018-09-14 13:32:07 -0700565 *timeout* (a float or int), if specified, can be used to control
566 the maximum number of seconds to wait before returning.
567
568 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400569 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700570 returned in the second set.
571
572 *return_when* indicates when this function should return. It must
573 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100574
575 .. tabularcolumns:: |l|L|
576
577 +-----------------------------+----------------------------------------+
578 | Constant | Description |
579 +=============================+========================================+
580 | :const:`FIRST_COMPLETED` | The function will return when any |
581 | | future finishes or is cancelled. |
582 +-----------------------------+----------------------------------------+
583 | :const:`FIRST_EXCEPTION` | The function will return when any |
584 | | future finishes by raising an |
585 | | exception. If no future raises an |
586 | | exception then it is equivalent to |
587 | | :const:`ALL_COMPLETED`. |
588 +-----------------------------+----------------------------------------+
589 | :const:`ALL_COMPLETED` | The function will return when all |
590 | | futures finish or are cancelled. |
591 +-----------------------------+----------------------------------------+
592
Yury Selivanov3faaa882018-09-14 13:32:07 -0700593 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
594 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100595
Andrew Svetlova4888792019-09-12 15:40:40 +0300596 .. deprecated:: 3.8
597
598 If any awaitable in *aws* is a coroutine, it is automatically
599 scheduled as a Task. Passing coroutines objects to
600 ``wait()`` directly is deprecated as it leads to
601 :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
602
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700603 .. deprecated-removed:: 3.8 3.10
604 The ``loop`` parameter. This function has been implicitly getting the
605 current running loop since 3.7. See
606 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
607 for more information.
608
Yury Selivanov996859a2018-09-25 14:51:21 -0400609 .. _asyncio_example_wait_coroutine:
610 .. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100611
Yury Selivanov996859a2018-09-25 14:51:21 -0400612 ``wait()`` schedules coroutines as Tasks automatically and later
613 returns those implicitly created Task objects in ``(done, pending)``
614 sets. Therefore the following code won't work as expected::
615
616 async def foo():
617 return 42
618
619 coro = foo()
620 done, pending = await asyncio.wait({coro})
621
622 if coro in done:
623 # This branch will never be run!
624
625 Here is how the above snippet can be fixed::
626
627 async def foo():
628 return 42
629
630 task = asyncio.create_task(foo())
631 done, pending = await asyncio.wait({task})
632
633 if task in done:
634 # Everything will work as expected now.
635
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700636 .. deprecated-removed:: 3.8 3.10
637
638 The ``loop`` parameter. This function has been implicitly getting the
639 current running loop since 3.7. See
640 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
641 for more information.
642
jack1142de927692020-05-13 20:55:12 +0200643 .. deprecated-removed:: 3.8 3.11
Matthias Bussonnierd0ebf132019-05-20 23:20:10 -0700644
Yury Selivanov996859a2018-09-25 14:51:21 -0400645 Passing coroutine objects to ``wait()`` directly is
646 deprecated.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100647
Victor Stinnerea3183f2013-12-03 01:08:00 +0100648
Andre Delfinodcc997c2020-12-16 22:37:28 -0300649.. function:: as_completed(aws, *, timeout=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700650
Yury Selivanove247b462018-09-20 12:43:59 -0400651 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100652 iterable concurrently. Return an iterator of coroutines.
Bar Harel13206b52020-05-24 02:14:31 +0300653 Each coroutine returned can be awaited to get the earliest next
Jakub Stasiak3d86d092020-11-02 11:56:35 +0100654 result from the iterable of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700655
656 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
657 all Futures are done.
658
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700659 .. deprecated-removed:: 3.8 3.10
660 The ``loop`` parameter. This function has been implicitly getting the
661 current running loop since 3.7. See
662 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
663 for more information.
664
Yury Selivanov3faaa882018-09-14 13:32:07 -0700665 Example::
666
Bar Harel13206b52020-05-24 02:14:31 +0300667 for coro in as_completed(aws):
668 earliest_result = await coro
Yury Selivanov3faaa882018-09-14 13:32:07 -0700669 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100670
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700671 .. deprecated-removed:: 3.8 3.10
672 The ``loop`` parameter. This function has been implicitly getting the
673 current running loop since 3.7. See
674 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
675 for more information.
676
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300677 .. deprecated:: 3.10
678 Deprecation warning is emitted if not all awaitable objects in the *aws*
679 iterable are Future-like objects and there is no running event loop.
680
Victor Stinner3e09e322013-12-03 01:22:06 +0100681
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400682Running in Threads
683==================
684
Andre Delfinodcc997c2020-12-16 22:37:28 -0300685.. coroutinefunction:: to_thread(func, /, *args, **kwargs)
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400686
687 Asynchronously run function *func* in a separate thread.
688
689 Any \*args and \*\*kwargs supplied for this function are directly passed
Jesús Cea989af252020-11-24 00:56:30 +0100690 to *func*. Also, the current :class:`contextvars.Context` is propagated,
Kyle Stanley0f562632020-05-21 01:20:43 -0400691 allowing context variables from the event loop thread to be accessed in the
692 separate thread.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400693
Kyle Stanley2b201362020-05-31 03:07:04 -0400694 Return a coroutine that can be awaited to get the eventual result of *func*.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400695
696 This coroutine function is primarily intended to be used for executing
697 IO-bound functions/methods that would otherwise block the event loop if
698 they were ran in the main thread. For example::
699
700 def blocking_io():
701 print(f"start blocking_io at {time.strftime('%X')}")
702 # Note that time.sleep() can be replaced with any blocking
703 # IO-bound operation, such as file operations.
704 time.sleep(1)
705 print(f"blocking_io complete at {time.strftime('%X')}")
706
707 async def main():
708 print(f"started main at {time.strftime('%X')}")
709
710 await asyncio.gather(
711 asyncio.to_thread(blocking_io),
712 asyncio.sleep(1))
713
714 print(f"finished main at {time.strftime('%X')}")
715
716
717 asyncio.run(main())
718
719 # Expected output:
720 #
721 # started main at 19:50:53
722 # start blocking_io at 19:50:53
723 # blocking_io complete at 19:50:54
724 # finished main at 19:50:54
725
726 Directly calling `blocking_io()` in any coroutine would block the event loop
727 for its duration, resulting in an additional 1 second of run time. Instead,
728 by using `asyncio.to_thread()`, we can run it in a separate thread without
729 blocking the event loop.
730
731 .. note::
732
733 Due to the :term:`GIL`, `asyncio.to_thread()` can typically only be used
734 to make IO-bound functions non-blocking. However, for extension modules
735 that release the GIL or alternative Python implementations that don't
736 have one, `asyncio.to_thread()` can also be used for CPU-bound functions.
737
Kyle Stanley0f562632020-05-21 01:20:43 -0400738 .. versionadded:: 3.9
739
Kyle Stanleycc2bbc22020-05-18 23:03:28 -0400740
Yury Selivanov3faaa882018-09-14 13:32:07 -0700741Scheduling From Other Threads
742=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100743
Yury Selivanov3faaa882018-09-14 13:32:07 -0700744.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100745
Yury Selivanov3faaa882018-09-14 13:32:07 -0700746 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100747
Yury Selivanov47150392018-09-18 17:55:44 -0400748 Return a :class:`concurrent.futures.Future` to wait for the result
749 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100750
Yury Selivanov3faaa882018-09-14 13:32:07 -0700751 This function is meant to be called from a different OS thread
752 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200753
Yury Selivanov3faaa882018-09-14 13:32:07 -0700754 # Create a coroutine
755 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500756
Yury Selivanov3faaa882018-09-14 13:32:07 -0700757 # Submit the coroutine to a given loop
758 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100759
Yury Selivanov3faaa882018-09-14 13:32:07 -0700760 # Wait for the result with an optional timeout argument
761 assert future.result(timeout) == 3
762
763 If an exception is raised in the coroutine, the returned Future
764 will be notified. It can also be used to cancel the task in
765 the event loop::
766
767 try:
768 result = future.result(timeout)
769 except asyncio.TimeoutError:
770 print('The coroutine took too long, cancelling the task...')
771 future.cancel()
772 except Exception as exc:
Mariatta9f43fbb2018-10-24 15:37:12 -0700773 print(f'The coroutine raised an exception: {exc!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700774 else:
Mariatta9f43fbb2018-10-24 15:37:12 -0700775 print(f'The coroutine returned: {result!r}')
Yury Selivanov3faaa882018-09-14 13:32:07 -0700776
777 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
778 section of the documentation.
779
Vaibhav Gupta3a810762018-12-26 20:17:17 +0530780 Unlike other asyncio functions this function requires the *loop*
Yury Selivanov3faaa882018-09-14 13:32:07 -0700781 argument to be passed explicitly.
782
783 .. versionadded:: 3.5.1
784
785
786Introspection
787=============
788
789
790.. function:: current_task(loop=None)
791
792 Return the currently running :class:`Task` instance, or ``None`` if
793 no task is running.
794
795 If *loop* is ``None`` :func:`get_running_loop` is used to get
796 the current loop.
797
798 .. versionadded:: 3.7
799
800
801.. function:: all_tasks(loop=None)
802
803 Return a set of not yet finished :class:`Task` objects run by
804 the loop.
805
806 If *loop* is ``None``, :func:`get_running_loop` is used for getting
807 current loop.
808
809 .. versionadded:: 3.7
810
811
812Task Object
813===========
814
Andre Delfinodcc997c2020-12-16 22:37:28 -0300815.. class:: Task(coro, *, loop=None, name=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700816
Yury Selivanovdb1a80e2018-09-21 16:23:15 -0400817 A :class:`Future-like <Future>` object that runs a Python
Yury Selivanov3faaa882018-09-14 13:32:07 -0700818 :ref:`coroutine <coroutine>`. Not thread-safe.
819
820 Tasks are used to run coroutines in event loops.
821 If a coroutine awaits on a Future, the Task suspends
822 the execution of the coroutine and waits for the completion
823 of the Future. When the Future is *done*, the execution of
824 the wrapped coroutine resumes.
825
826 Event loops use cooperative scheduling: an event loop runs
827 one Task at a time. While a Task awaits for the completion of a
828 Future, the event loop runs other Tasks, callbacks, or performs
829 IO operations.
830
831 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400832 Tasks, or the low-level :meth:`loop.create_task` or
833 :func:`ensure_future` functions. Manual instantiation of Tasks
834 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700835
836 To cancel a running Task use the :meth:`cancel` method. Calling it
837 will cause the Task to throw a :exc:`CancelledError` exception into
838 the wrapped coroutine. If a coroutine is awaiting on a Future
839 object during cancellation, the Future object will be cancelled.
840
841 :meth:`cancelled` can be used to check if the Task was cancelled.
842 The method returns ``True`` if the wrapped coroutine did not
843 suppress the :exc:`CancelledError` exception and was actually
844 cancelled.
845
846 :class:`asyncio.Task` inherits from :class:`Future` all of its
847 APIs except :meth:`Future.set_result` and
848 :meth:`Future.set_exception`.
849
850 Tasks support the :mod:`contextvars` module. When a Task
851 is created it copies the current context and later runs its
852 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400853
854 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700855 Added support for the :mod:`contextvars` module.
856
857 .. versionchanged:: 3.8
858 Added the ``name`` parameter.
859
Andrew Svetlova4888792019-09-12 15:40:40 +0300860 .. deprecated-removed:: 3.8 3.10
861 The *loop* parameter.
862
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300863 .. deprecated:: 3.10
864 Deprecation warning is emitted if *loop* is not specified
865 and there is no running event loop.
866
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700867 .. method:: cancel(msg=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700868
869 Request the Task to be cancelled.
870
871 This arranges for a :exc:`CancelledError` exception to be thrown
872 into the wrapped coroutine on the next cycle of the event loop.
873
874 The coroutine then has a chance to clean up or even deny the
875 request by suppressing the exception with a :keyword:`try` ...
876 ... ``except CancelledError`` ... :keyword:`finally` block.
877 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
878 not guarantee that the Task will be cancelled, although
879 suppressing cancellation completely is not common and is actively
880 discouraged.
881
Chris Jerdonek1ce58412020-05-15 16:55:50 -0700882 .. versionchanged:: 3.9
883 Added the ``msg`` parameter.
884
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700885 .. _asyncio_example_task_cancel:
886
Yury Selivanov3faaa882018-09-14 13:32:07 -0700887 The following example illustrates how coroutines can intercept
888 the cancellation request::
889
890 async def cancel_me():
891 print('cancel_me(): before sleep')
892
893 try:
894 # Wait for 1 hour
895 await asyncio.sleep(3600)
896 except asyncio.CancelledError:
897 print('cancel_me(): cancel sleep')
898 raise
899 finally:
900 print('cancel_me(): after sleep')
901
902 async def main():
903 # Create a "cancel_me" Task
904 task = asyncio.create_task(cancel_me())
905
906 # Wait for 1 second
907 await asyncio.sleep(1)
908
909 task.cancel()
910 try:
911 await task
912 except asyncio.CancelledError:
913 print("main(): cancel_me is cancelled now")
914
915 asyncio.run(main())
916
917 # Expected output:
918 #
919 # cancel_me(): before sleep
920 # cancel_me(): cancel sleep
921 # cancel_me(): after sleep
922 # main(): cancel_me is cancelled now
923
924 .. method:: cancelled()
925
926 Return ``True`` if the Task is *cancelled*.
927
928 The Task is *cancelled* when the cancellation was requested with
929 :meth:`cancel` and the wrapped coroutine propagated the
930 :exc:`CancelledError` exception thrown into it.
931
932 .. method:: done()
933
934 Return ``True`` if the Task is *done*.
935
936 A Task is *done* when the wrapped coroutine either returned
937 a value, raised an exception, or the Task was cancelled.
938
Yury Selivanove247b462018-09-20 12:43:59 -0400939 .. method:: result()
940
941 Return the result of the Task.
942
943 If the Task is *done*, the result of the wrapped coroutine
944 is returned (or if the coroutine raised an exception, that
945 exception is re-raised.)
946
947 If the Task has been *cancelled*, this method raises
948 a :exc:`CancelledError` exception.
949
950 If the Task's result isn't yet available, this method raises
951 a :exc:`InvalidStateError` exception.
952
953 .. method:: exception()
954
955 Return the exception of the Task.
956
957 If the wrapped coroutine raised an exception that exception
958 is returned. If the wrapped coroutine returned normally
959 this method returns ``None``.
960
961 If the Task has been *cancelled*, this method raises a
962 :exc:`CancelledError` exception.
963
964 If the Task isn't *done* yet, this method raises an
965 :exc:`InvalidStateError` exception.
966
967 .. method:: add_done_callback(callback, *, context=None)
968
969 Add a callback to be run when the Task is *done*.
970
971 This method should only be used in low-level callback-based code.
972
973 See the documentation of :meth:`Future.add_done_callback`
974 for more details.
975
976 .. method:: remove_done_callback(callback)
977
978 Remove *callback* from the callbacks list.
979
980 This method should only be used in low-level callback-based code.
981
982 See the documentation of :meth:`Future.remove_done_callback`
983 for more details.
984
Andre Delfinodcc997c2020-12-16 22:37:28 -0300985 .. method:: get_stack(*, limit=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700986
987 Return the list of stack frames for this Task.
988
989 If the wrapped coroutine is not done, this returns the stack
990 where it is suspended. If the coroutine has completed
991 successfully or was cancelled, this returns an empty list.
992 If the coroutine was terminated by an exception, this returns
993 the list of traceback frames.
994
995 The frames are always ordered from oldest to newest.
996
997 Only one stack frame is returned for a suspended coroutine.
998
999 The optional *limit* argument sets the maximum number of frames
1000 to return; by default all available frames are returned.
1001 The ordering of the returned list differs depending on whether
1002 a stack or a traceback is returned: the newest frames of a
1003 stack are returned, but the oldest frames of a traceback are
1004 returned. (This matches the behavior of the traceback module.)
1005
Andre Delfinodcc997c2020-12-16 22:37:28 -03001006 .. method:: print_stack(*, limit=None, file=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -07001007
1008 Print the stack or traceback for this Task.
1009
1010 This produces output similar to that of the traceback module
1011 for the frames retrieved by :meth:`get_stack`.
1012
1013 The *limit* argument is passed to :meth:`get_stack` directly.
1014
1015 The *file* argument is an I/O stream to which the output
1016 is written; by default output is written to :data:`sys.stderr`.
1017
Alex Grönholm98ef9202019-05-30 18:30:09 +03001018 .. method:: get_coro()
1019
1020 Return the coroutine object wrapped by the :class:`Task`.
1021
1022 .. versionadded:: 3.8
1023
Yury Selivanov3faaa882018-09-14 13:32:07 -07001024 .. method:: get_name()
1025
1026 Return the name of the Task.
1027
1028 If no name has been explicitly assigned to the Task, the default
1029 asyncio Task implementation generates a default name during
1030 instantiation.
1031
1032 .. versionadded:: 3.8
1033
1034 .. method:: set_name(value)
1035
1036 Set the name of the Task.
1037
1038 The *value* argument can be any object, which is then
1039 converted to a string.
1040
1041 In the default Task implementation, the name will be visible
1042 in the :func:`repr` output of a task object.
1043
1044 .. versionadded:: 3.8
1045
Yury Selivanov3faaa882018-09-14 13:32:07 -07001046
1047.. _asyncio_generator_based_coro:
1048
1049Generator-based Coroutines
1050==========================
1051
1052.. note::
1053
1054 Support for generator-based coroutines is **deprecated** and
Yury Selivanovfad6af22018-09-25 17:44:52 -04001055 is scheduled for removal in Python 3.10.
Yury Selivanov3faaa882018-09-14 13:32:07 -07001056
1057Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001058Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -07001059on Futures and other coroutines.
1060
1061Generator-based coroutines should be decorated with
1062:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
1063enforced.
1064
1065
1066.. decorator:: coroutine
1067
1068 Decorator to mark generator-based coroutines.
1069
1070 This decorator enables legacy generator-based coroutines to be
1071 compatible with async/await code::
1072
1073 @asyncio.coroutine
1074 def old_style_coroutine():
1075 yield from asyncio.sleep(1)
1076
1077 async def main():
1078 await old_style_coroutine()
1079
Yury Selivanov3faaa882018-09-14 13:32:07 -07001080 This decorator should not be used for :keyword:`async def`
1081 coroutines.
1082
Andrew Svetlov68b34a72019-05-16 17:52:10 +03001083 .. deprecated-removed:: 3.8 3.10
1084
1085 Use :keyword:`async def` instead.
1086
Yury Selivanov3faaa882018-09-14 13:32:07 -07001087.. function:: iscoroutine(obj)
1088
1089 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
1090
1091 This method is different from :func:`inspect.iscoroutine` because
Yury Selivanov59ee5b12018-09-27 15:48:30 -04001092 it returns ``True`` for generator-based coroutines.
Yury Selivanov3faaa882018-09-14 13:32:07 -07001093
1094.. function:: iscoroutinefunction(func)
1095
1096 Return ``True`` if *func* is a :ref:`coroutine function
1097 <coroutine>`.
1098
1099 This method is different from :func:`inspect.iscoroutinefunction`
1100 because it returns ``True`` for generator-based coroutine functions
1101 decorated with :func:`@coroutine <coroutine>`.