blob: 2753998745efa48abcfbbd0b33332496993ca92e [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov512d7102018-09-17 19:35:30 -04003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov512d7102018-09-17 19:35:30 -04008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov512d7102018-09-17 19:35:30 -040011.. 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 Selivanov512d7102018-09-17 19:35:30 -040019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov512d7102018-09-17 19:35:30 -040021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
23of code prints "hello", waits 1 second, and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
Yury Selivanov512d7102018-09-17 19:35:30 -040025 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010026
Yury Selivanov512d7102018-09-17 19:35:30 -040027 >>> async def main():
28 ... print('hello')
29 ... await asyncio.sleep(1)
30 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
Yury Selivanov512d7102018-09-17 19:35:30 -040032 >>> asyncio.run(main())
33 hello
34 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Yury Selivanov512d7102018-09-17 19:35:30 -040036Note that simply calling a coroutine will not schedule it to
37be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010038
Yury Selivanov512d7102018-09-17 19:35:30 -040039 >>> main()
40 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010041
Yury Selivanov512d7102018-09-17 19:35:30 -040042To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010043
Yury Selivanov512d7102018-09-17 19:35:30 -040044* The :func:`asyncio.run` function to run the top-level
45 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010046
Yury Selivanov512d7102018-09-17 19:35:30 -040047* Awaiting on a coroutine. The following snippet of code will
48 print "hello" after waiting for 1 second, and then print "world"
49 after waiting for *another* 2 seconds::
Victor Stinnerea3183f2013-12-03 01:08:00 +010050
Yury Selivanov512d7102018-09-17 19:35:30 -040051 import asyncio
52 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Yury Selivanov512d7102018-09-17 19:35:30 -040054 async def say_after(delay, what):
55 await asyncio.sleep(delay)
56 print(what)
57
58 async def main():
59 print('started at', time.strftime('%X'))
60
61 await say_after(1, 'hello')
62 await say_after(2, 'world')
63
64 print('finished at', time.strftime('%X'))
65
66 asyncio.run(main())
67
68 Expected output::
69
70 started at 17:13:52
71 hello
72 world
73 finished at 17:13:55
74
75* The :func:`asyncio.create_task` function to run coroutines
76 concurrently as asyncio :class:`Tasks <Task>`.
77
Miss Islington (bot)9a89fd62018-09-17 23:27:07 -070078 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040079 *concurrently*::
80
81 async def main():
82 task1 = asyncio.create_task(
83 say_after(1, 'hello'))
84
85 task2 = asyncio.create_task(
86 say_after(2, 'world'))
87
88 print('started at', time.strftime('%X'))
89
90 # Wait until both tasks are completed (should take
91 # around 2 seconds.)
92 await task1
93 await task2
94
95 print('finished at', time.strftime('%X'))
96
97 Note that expected output now shows that the snippet runs
98 1 second faster than before::
99
100 started at 17:14:32
101 hello
102 world
103 finished at 17:14:34
104
105Note that in this documentation the term "coroutine" can be used for
106two closely related concepts:
107
108* a *coroutine function*: an :keyword:`async def` function;
109
110* a *coroutine object*: object returned by calling a
111 *coroutine function*.
Victor Stinner337e03f2014-08-11 01:11:13 +0200112
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113
Yury Selivanov512d7102018-09-17 19:35:30 -0400114Running an asyncio Program
115==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
Elvis Pranskevichus15f3d0c2018-05-19 23:39:45 -0400117.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500118
119 This function runs the passed coroutine, taking care of
120 managing the asyncio event loop and finalizing asynchronous
121 generators.
122
123 This function cannot be called when another asyncio event loop is
124 running in the same thread.
125
Yury Selivanov512d7102018-09-17 19:35:30 -0400126 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500127
128 This function always creates a new event loop and closes it at
129 the end. It should be used as a main entry point for asyncio
130 programs, and should ideally only be called once.
131
132 .. versionadded:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400133 **Important:** this function has been added to asyncio in
134 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500135
136
Yury Selivanov512d7102018-09-17 19:35:30 -0400137Creating Tasks
138==============
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100139
Yury Selivanov512d7102018-09-17 19:35:30 -0400140.. function:: create_task(coro)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100141
Yury Selivanov512d7102018-09-17 19:35:30 -0400142 Wrap the *coro* :ref:`coroutine <coroutine>` into a task and schedule
143 its execution. Return the task object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100144
Yury Selivanov512d7102018-09-17 19:35:30 -0400145 The task is executed in the loop returned by :func:`get_running_loop`,
146 :exc:`RuntimeError` is raised if there is no running loop in
147 current thread.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100148
Yury Selivanov512d7102018-09-17 19:35:30 -0400149 .. versionadded:: 3.7
Victor Stinner7f314ed2014-10-15 18:49:16 +0200150
151
Yury Selivanov512d7102018-09-17 19:35:30 -0400152Sleeping
153========
Victor Stinner7f314ed2014-10-15 18:49:16 +0200154
Yury Selivanov512d7102018-09-17 19:35:30 -0400155.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinner7f314ed2014-10-15 18:49:16 +0200156
Yury Selivanov512d7102018-09-17 19:35:30 -0400157 Block for *delay* seconds.
158
159 If *result* is provided, it is returned to the caller
160 when the coroutine completes.
161
162 .. _asyncio_example_sleep:
163
164 Example of coroutine displaying the current date every second
165 for 5 seconds::
Victor Stinner7f314ed2014-10-15 18:49:16 +0200166
167 import asyncio
168 import datetime
169
Yury Selivanov02a0a192017-12-14 09:42:21 -0500170 async def display_date():
171 loop = asyncio.get_running_loop()
Yury Selivanov66f88282015-06-24 11:04:15 -0400172 end_time = loop.time() + 5.0
173 while True:
174 print(datetime.datetime.now())
175 if (loop.time() + 1.0) >= end_time:
176 break
177 await asyncio.sleep(1)
178
Yury Selivanov02a0a192017-12-14 09:42:21 -0500179 asyncio.run(display_date())
Yury Selivanov66f88282015-06-24 11:04:15 -0400180
Victor Stinner7f314ed2014-10-15 18:49:16 +0200181
Yury Selivanov512d7102018-09-17 19:35:30 -0400182Running Tasks Concurrently
183==========================
Victor Stinner7f314ed2014-10-15 18:49:16 +0200184
Yury Selivanov512d7102018-09-17 19:35:30 -0400185.. function:: gather(\*fs, loop=None, return_exceptions=False)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100186
Yury Selivanov512d7102018-09-17 19:35:30 -0400187 Return a Future aggregating results from the given coroutine objects,
188 Tasks, or Futures.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100189
Yury Selivanov512d7102018-09-17 19:35:30 -0400190 If all Tasks/Futures are completed successfully, the result is an
191 aggregate list of returned values. The result values are in the
192 order of the original *fs* sequence.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100193
Yury Selivanov512d7102018-09-17 19:35:30 -0400194 All coroutines in the *fs* list are automatically
195 scheduled as :class:`Tasks <Task>`.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100196
Yury Selivanov512d7102018-09-17 19:35:30 -0400197 If *return_exceptions* is ``True``, exceptions in the Tasks/Futures
198 are treated the same as successful results, and gathered in the
199 result list. Otherwise, the first raised exception is immediately
200 propagated to the returned Future.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100201
Yury Selivanov512d7102018-09-17 19:35:30 -0400202 If the outer Future is *cancelled*, all submitted Tasks/Futures
203 (that have not completed yet) are also *cancelled*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100204
Yury Selivanov512d7102018-09-17 19:35:30 -0400205 If any child is *cancelled*, it is treated as if it raised
206 :exc:`CancelledError` -- the outer Future is **not** cancelled in
207 this case. This is to prevent the cancellation of one submitted
208 Task/Future to cause other Tasks/Futures to be cancelled.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100209
Yury Selivanov512d7102018-09-17 19:35:30 -0400210 All futures must share the same event loop.
Victor Stinner83704962015-02-25 14:24:15 +0100211
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700212 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400213 If the *gather* itself is cancelled, the cancellation is
214 propagated regardless of *return_exceptions*.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700215
Yury Selivanov512d7102018-09-17 19:35:30 -0400216 .. _asyncio_example_gather:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100217
218 Example::
219
Yury Selivanov512d7102018-09-17 19:35:30 -0400220 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100221
Yury Selivanov512d7102018-09-17 19:35:30 -0400222 async def factorial(name, number):
223 f = 1
224 for i in range(2, number + 1):
225 print(f"Task {name}: Compute factorial({i})...")
226 await asyncio.sleep(1)
227 f *= i
228 print(f"Task {name}: factorial({number}) = {f}")
Victor Stinnerea3183f2013-12-03 01:08:00 +0100229
Yury Selivanov512d7102018-09-17 19:35:30 -0400230 async def main():
231 await asyncio.gather(
232 factorial("A", 2),
233 factorial("B", 3),
234 factorial("C", 4),
Miss Islington (bot)ee2ff1a2018-09-17 23:27:27 -0700235 )
Victor Stinnerea3183f2013-12-03 01:08:00 +0100236
Yury Selivanov512d7102018-09-17 19:35:30 -0400237 asyncio.run(main())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100238
Yury Selivanov512d7102018-09-17 19:35:30 -0400239 # Expected output:
240 #
241 # Task A: Compute factorial(2)...
242 # Task B: Compute factorial(2)...
243 # Task C: Compute factorial(2)...
244 # Task A: factorial(2) = 2
245 # Task B: Compute factorial(3)...
246 # Task C: Compute factorial(3)...
247 # Task B: factorial(3) = 6
248 # Task C: Compute factorial(4)...
249 # Task C: factorial(4) = 24
Victor Stinnerea3183f2013-12-03 01:08:00 +0100250
Victor Stinnerea3183f2013-12-03 01:08:00 +0100251
Yury Selivanov512d7102018-09-17 19:35:30 -0400252Shielding Tasks From Cancellation
253=================================
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400254
Yury Selivanov512d7102018-09-17 19:35:30 -0400255.. coroutinefunction:: shield(fut, \*, loop=None)
Yury Selivanove319ab02015-12-15 00:45:24 -0500256
Yury Selivanov512d7102018-09-17 19:35:30 -0400257 Wait for a Future/Task while protecting it from being cancelled.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200258
Yury Selivanov512d7102018-09-17 19:35:30 -0400259 *fut* can be a coroutine, a Task, or a Future-like object. If
260 *fut* is a coroutine it is automatically scheduled as a
261 :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262
263 The statement::
264
Andrew Svetlov88743422017-12-11 17:35:49 +0200265 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
Yury Selivanov512d7102018-09-17 19:35:30 -0400267 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
Andrew Svetlov88743422017-12-11 17:35:49 +0200269 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270
Yury Selivanov512d7102018-09-17 19:35:30 -0400271 *except* that if the coroutine containing it is cancelled, the
272 Task running in ``something()`` is not cancelled. From the point
273 of view of ``something()``, the cancellation did not happen.
274 Although its caller is still cancelled, so the "await" expression
275 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100276
Yury Selivanov512d7102018-09-17 19:35:30 -0400277 If ``something()`` is cancelled by other means (i.e. from within
278 itself) that would also cancel ``shield()``.
279
280 If it is desired to completely ignore cancellation (not recommended)
281 the ``shield()`` function should be combined with a try/except
282 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
284 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200285 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100286 except CancelledError:
287 res = None
288
Yury Selivanov950204d2016-05-16 16:23:00 -0400289
Yury Selivanov512d7102018-09-17 19:35:30 -0400290Timeouts
291========
292
293.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
294
295 Wait for a coroutine, Task, or Future to complete with timeout.
296
297 *fut* can be a coroutine, a Task, or a Future-like object. If
298 *fut* is a coroutine it is automatically scheduled as a
299 :class:`Task`.
300
301 *timeout* can either be ``None`` or a float or int number of seconds
302 to wait for. If *timeout* is ``None``, block until the future
303 completes.
304
305 If a timeout occurs, it cancels the task and raises
306 :exc:`asyncio.TimeoutError`.
307
308 To avoid the task cancellation, wrap it in :func:`shield`.
309
310 The function will wait until the future is actually cancelled,
311 so the total wait time may exceed the *timeout*.
312
313 If the wait is cancelled, the future *fut* is also cancelled.
314
315 .. _asyncio_example_waitfor:
316
317 Example::
318
319 async def eternity():
320 # Sleep for one hour
321 await asyncio.sleep(3600)
322 print('yay!')
323
324 async def main():
325 # Wait for at most 1 second
326 try:
327 await asyncio.wait_for(eternity(), timeout=1.0)
328 except asyncio.TimeoutError:
329 print('timeout!')
330
331 asyncio.run(main())
332
333 # Expected output:
334 #
335 # timeout!
336
337 .. versionchanged:: 3.7
338 When *fut* is cancelled due to a timeout, ``wait_for`` waits
339 for *fut* to be cancelled. Previously, it raised
340 :exc:`asyncio.TimeoutError` immediately.
341
342
343Waiting Primitives
344==================
345
346.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200347 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348
Yury Selivanov512d7102018-09-17 19:35:30 -0400349 Wait for a set of coroutines, Tasks, or Futures to complete.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
Yury Selivanov512d7102018-09-17 19:35:30 -0400351 *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines
352 are automatically scheduled as :class:`Tasks <Task>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200353
Yury Selivanov512d7102018-09-17 19:35:30 -0400354 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100355
Yury Selivanov512d7102018-09-17 19:35:30 -0400356 *timeout* (a float or int), if specified, can be used to control
357 the maximum number of seconds to wait before returning.
358
359 Note that this function does not raise :exc:`asyncio.TimeoutError`.
360 Futures or Tasks that aren't done when the timeout occurs are simply
361 returned in the second set.
362
363 *return_when* indicates when this function should return. It must
364 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100365
366 .. tabularcolumns:: |l|L|
367
368 +-----------------------------+----------------------------------------+
369 | Constant | Description |
370 +=============================+========================================+
371 | :const:`FIRST_COMPLETED` | The function will return when any |
372 | | future finishes or is cancelled. |
373 +-----------------------------+----------------------------------------+
374 | :const:`FIRST_EXCEPTION` | The function will return when any |
375 | | future finishes by raising an |
376 | | exception. If no future raises an |
377 | | exception then it is equivalent to |
378 | | :const:`ALL_COMPLETED`. |
379 +-----------------------------+----------------------------------------+
380 | :const:`ALL_COMPLETED` | The function will return when all |
381 | | futures finish or are cancelled. |
382 +-----------------------------+----------------------------------------+
383
Yury Selivanov512d7102018-09-17 19:35:30 -0400384 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
385 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100386
387 Usage::
388
Andrew Svetlov88743422017-12-11 17:35:49 +0200389 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100390
Victor Stinnerea3183f2013-12-03 01:08:00 +0100391
Yury Selivanov512d7102018-09-17 19:35:30 -0400392.. function:: as_completed(fs, \*, loop=None, timeout=None)
393
394 Return an iterator of awaitables which return
395 :class:`Future` instances.
396
397 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
398 all Futures are done.
399
400 Example::
401
402 for f in as_completed(fs):
403 result = await f
404 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100405
Victor Stinner3e09e322013-12-03 01:22:06 +0100406
Yury Selivanov512d7102018-09-17 19:35:30 -0400407Scheduling From Other Threads
408=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100409
Yury Selivanov512d7102018-09-17 19:35:30 -0400410.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100411
Yury Selivanov512d7102018-09-17 19:35:30 -0400412 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100413
Yury Selivanov512d7102018-09-17 19:35:30 -0400414 Return a :class:`concurrent.futures.Future` to access the result.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100415
Yury Selivanov512d7102018-09-17 19:35:30 -0400416 This function is meant to be called from a different OS thread
417 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200418
Yury Selivanov512d7102018-09-17 19:35:30 -0400419 # Create a coroutine
420 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500421
Yury Selivanov512d7102018-09-17 19:35:30 -0400422 # Submit the coroutine to a given loop
423 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100424
Yury Selivanov512d7102018-09-17 19:35:30 -0400425 # Wait for the result with an optional timeout argument
426 assert future.result(timeout) == 3
427
428 If an exception is raised in the coroutine, the returned Future
429 will be notified. It can also be used to cancel the task in
430 the event loop::
431
432 try:
433 result = future.result(timeout)
434 except asyncio.TimeoutError:
435 print('The coroutine took too long, cancelling the task...')
436 future.cancel()
437 except Exception as exc:
438 print('The coroutine raised an exception: {!r}'.format(exc))
439 else:
440 print('The coroutine returned: {!r}'.format(result))
441
442 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
443 section of the documentation.
444
445 Unlike other asyncio functions this functions requires the *loop*
446 argument to be passed explicitly.
447
448 .. versionadded:: 3.5.1
449
450
451Introspection
452=============
453
454
455.. function:: current_task(loop=None)
456
457 Return the currently running :class:`Task` instance, or ``None`` if
458 no task is running.
459
460 If *loop* is ``None`` :func:`get_running_loop` is used to get
461 the current loop.
462
463 .. versionadded:: 3.7
464
465
466.. function:: all_tasks(loop=None)
467
468 Return a set of not yet finished :class:`Task` objects run by
469 the loop.
470
471 If *loop* is ``None``, :func:`get_running_loop` is used for getting
472 current loop.
473
474 .. versionadded:: 3.7
475
476
477Task Object
478===========
479
480.. class:: Task(coro, \*, loop=None)
481
482 A :class:`Future`-like object that wraps a Python
483 :ref:`coroutine <coroutine>`. Not thread-safe.
484
485 Tasks are used to run coroutines in event loops.
486 If a coroutine awaits on a Future, the Task suspends
487 the execution of the coroutine and waits for the completion
488 of the Future. When the Future is *done*, the execution of
489 the wrapped coroutine resumes.
490
491 Event loops use cooperative scheduling: an event loop runs
492 one Task at a time. While a Task awaits for the completion of a
493 Future, the event loop runs other Tasks, callbacks, or performs
494 IO operations.
495
496 Use the high-level :func:`asyncio.create_task` function to create
497 Tasks, or the low-level :meth:`loop.create_task` or
498 :func:`ensure_future` functions. Manual instantiation of Tasks
499 is discouraged.
500
501 To cancel a running Task use the :meth:`cancel` method. Calling it
502 will cause the Task to throw a :exc:`CancelledError` exception into
503 the wrapped coroutine. If a coroutine is awaiting on a Future
504 object during cancellation, the Future object will be cancelled.
505
506 :meth:`cancelled` can be used to check if the Task was cancelled.
507 The method returns ``True`` if the wrapped coroutine did not
508 suppress the :exc:`CancelledError` exception and was actually
509 cancelled.
510
511 :class:`asyncio.Task` inherits from :class:`Future` all of its
512 APIs except :meth:`Future.set_result` and
513 :meth:`Future.set_exception`.
514
515 Tasks support the :mod:`contextvars` module. When a Task
516 is created it copies the current context and later runs its
517 coroutine in the copied context.
Miss Islington (bot)d8948c52018-05-29 15:37:06 -0700518
519 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400520 Added support for the :mod:`contextvars` module.
521
522 .. method:: cancel()
523
524 Request the Task to be cancelled.
525
526 This arranges for a :exc:`CancelledError` exception to be thrown
527 into the wrapped coroutine on the next cycle of the event loop.
528
529 The coroutine then has a chance to clean up or even deny the
530 request by suppressing the exception with a :keyword:`try` ...
531 ... ``except CancelledError`` ... :keyword:`finally` block.
532 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
533 not guarantee that the Task will be cancelled, although
534 suppressing cancellation completely is not common and is actively
535 discouraged.
536
537 .. _asyncio_example_task_cancel:
538
539 The following example illustrates how coroutines can intercept
540 the cancellation request::
541
542 async def cancel_me():
543 print('cancel_me(): before sleep')
544
545 try:
546 # Wait for 1 hour
547 await asyncio.sleep(3600)
548 except asyncio.CancelledError:
549 print('cancel_me(): cancel sleep')
550 raise
551 finally:
552 print('cancel_me(): after sleep')
553
554 async def main():
555 # Create a "cancel_me" Task
556 task = asyncio.create_task(cancel_me())
557
558 # Wait for 1 second
559 await asyncio.sleep(1)
560
561 task.cancel()
562 try:
563 await task
564 except asyncio.CancelledError:
565 print("main(): cancel_me is cancelled now")
566
567 asyncio.run(main())
568
569 # Expected output:
570 #
571 # cancel_me(): before sleep
572 # cancel_me(): cancel sleep
573 # cancel_me(): after sleep
574 # main(): cancel_me is cancelled now
575
576 .. method:: cancelled()
577
578 Return ``True`` if the Task is *cancelled*.
579
580 The Task is *cancelled* when the cancellation was requested with
581 :meth:`cancel` and the wrapped coroutine propagated the
582 :exc:`CancelledError` exception thrown into it.
583
584 .. method:: done()
585
586 Return ``True`` if the Task is *done*.
587
588 A Task is *done* when the wrapped coroutine either returned
589 a value, raised an exception, or the Task was cancelled.
590
591 .. method:: get_stack(\*, limit=None)
592
593 Return the list of stack frames for this Task.
594
595 If the wrapped coroutine is not done, this returns the stack
596 where it is suspended. If the coroutine has completed
597 successfully or was cancelled, this returns an empty list.
598 If the coroutine was terminated by an exception, this returns
599 the list of traceback frames.
600
601 The frames are always ordered from oldest to newest.
602
603 Only one stack frame is returned for a suspended coroutine.
604
605 The optional *limit* argument sets the maximum number of frames
606 to return; by default all available frames are returned.
607 The ordering of the returned list differs depending on whether
608 a stack or a traceback is returned: the newest frames of a
609 stack are returned, but the oldest frames of a traceback are
610 returned. (This matches the behavior of the traceback module.)
611
612 .. method:: print_stack(\*, limit=None, file=None)
613
614 Print the stack or traceback for this Task.
615
616 This produces output similar to that of the traceback module
617 for the frames retrieved by :meth:`get_stack`.
618
619 The *limit* argument is passed to :meth:`get_stack` directly.
620
621 The *file* argument is an I/O stream to which the output
622 is written; by default output is written to :data:`sys.stderr`.
623
624 .. classmethod:: all_tasks(loop=None)
625
626 Return a set of all tasks for an event loop.
627
628 By default all tasks for the current event loop are returned.
629 If *loop* is ``None``, the :func:`get_event_loop` function
630 is used to get the current loop.
631
632 This method is **deprecated** and will be removed in
633 Python 3.9. Use the :func:`all_tasks` function instead.
634
635 .. classmethod:: current_task(loop=None)
636
637 Return the currently running task or ``None``.
638
639 If *loop* is ``None``, the :func:`get_event_loop` function
640 is used to get the current loop.
641
642 This method is **deprecated** and will be removed in
643 Python 3.9. Use the :func:`current_task` function instead.
644
645
646.. _asyncio_generator_based_coro:
647
648Generator-based Coroutines
649==========================
650
651.. note::
652
653 Support for generator-based coroutines is **deprecated** and
654 is scheduled for removal in Python 4.0.
655
656Generator-based coroutines predate async/await syntax. They are
657Python generators that use ``yield from`` expressions to await
658on Futures and other coroutines.
659
660Generator-based coroutines should be decorated with
661:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
662enforced.
663
664
665.. decorator:: coroutine
666
667 Decorator to mark generator-based coroutines.
668
669 This decorator enables legacy generator-based coroutines to be
670 compatible with async/await code::
671
672 @asyncio.coroutine
673 def old_style_coroutine():
674 yield from asyncio.sleep(1)
675
676 async def main():
677 await old_style_coroutine()
678
679 This decorator is **deprecated** and is scheduled for removal in
680 Python 4.0.
681
682 This decorator should not be used for :keyword:`async def`
683 coroutines.
684
685.. function:: iscoroutine(obj)
686
687 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
688
689 This method is different from :func:`inspect.iscoroutine` because
690 it returns ``True`` for generator-based coroutines decorated with
691 :func:`@coroutine <coroutine>`.
692
693.. function:: iscoroutinefunction(func)
694
695 Return ``True`` if *func* is a :ref:`coroutine function
696 <coroutine>`.
697
698 This method is different from :func:`inspect.iscoroutinefunction`
699 because it returns ``True`` for generator-based coroutine functions
700 decorated with :func:`@coroutine <coroutine>`.