blob: 45b8b604200e776a596c86b60e7268e565c18da6 [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
Miss Islington (bot)45452b72018-09-18 00:00:58 -070023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov512d7102018-09-17 19:35:30 -040026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov512d7102018-09-17 19:35:30 -040028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov512d7102018-09-17 19:35:30 -040033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov512d7102018-09-17 19:35:30 -040037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov512d7102018-09-17 19:35:30 -040040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov512d7102018-09-17 19:35:30 -040043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Yury Selivanov512d7102018-09-17 19:35:30 -040045* The :func:`asyncio.run` function to run the top-level
46 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Yury Selivanov512d7102018-09-17 19:35:30 -040048* Awaiting on a coroutine. The following snippet of code will
49 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 Selivanov512d7102018-09-17 19:35:30 -040052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov512d7102018-09-17 19:35:30 -040055 async def say_after(delay, what):
56 await asyncio.sleep(delay)
57 print(what)
58
59 async def main():
60 print('started at', time.strftime('%X'))
61
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
65 print('finished at', time.strftime('%X'))
66
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
76* The :func:`asyncio.create_task` function to run coroutines
77 concurrently as asyncio :class:`Tasks <Task>`.
78
Miss Islington (bot)9a89fd62018-09-17 23:27:07 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040080 *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
89 print('started at', time.strftime('%X'))
90
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
96 print('finished at', time.strftime('%X'))
97
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
106Note that in this documentation the term "coroutine" can be used for
107two closely related concepts:
108
109* a *coroutine function*: an :keyword:`async def` function;
110
111* a *coroutine object*: object returned by calling a
112 *coroutine function*.
Victor Stinner337e03f2014-08-11 01:11:13 +0200113
Victor Stinnerea3183f2013-12-03 01:08:00 +0100114
Yury Selivanov512d7102018-09-17 19:35:30 -0400115Running an asyncio Program
116==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100117
Elvis Pranskevichus15f3d0c2018-05-19 23:39:45 -0400118.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500119
120 This function runs the passed coroutine, taking care of
121 managing the asyncio event loop and finalizing asynchronous
122 generators.
123
124 This function cannot be called when another asyncio event loop is
125 running in the same thread.
126
Yury Selivanov512d7102018-09-17 19:35:30 -0400127 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500128
129 This function always creates a new event loop and closes it at
130 the end. It should be used as a main entry point for asyncio
131 programs, and should ideally only be called once.
132
133 .. versionadded:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400134 **Important:** this function has been added to asyncio in
135 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500136
137
Yury Selivanov512d7102018-09-17 19:35:30 -0400138Creating Tasks
139==============
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100140
Yury Selivanov512d7102018-09-17 19:35:30 -0400141.. function:: create_task(coro)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100142
Yury Selivanov512d7102018-09-17 19:35:30 -0400143 Wrap the *coro* :ref:`coroutine <coroutine>` into a task and schedule
144 its execution. Return the task object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100145
Yury Selivanov512d7102018-09-17 19:35:30 -0400146 The task is executed in the loop returned by :func:`get_running_loop`,
147 :exc:`RuntimeError` is raised if there is no running loop in
148 current thread.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100149
Yury Selivanov512d7102018-09-17 19:35:30 -0400150 .. versionadded:: 3.7
Victor Stinner7f314ed2014-10-15 18:49:16 +0200151
152
Yury Selivanov512d7102018-09-17 19:35:30 -0400153Sleeping
154========
Victor Stinner7f314ed2014-10-15 18:49:16 +0200155
Yury Selivanov512d7102018-09-17 19:35:30 -0400156.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinner7f314ed2014-10-15 18:49:16 +0200157
Yury Selivanov512d7102018-09-17 19:35:30 -0400158 Block for *delay* seconds.
159
160 If *result* is provided, it is returned to the caller
161 when the coroutine completes.
162
163 .. _asyncio_example_sleep:
164
165 Example of coroutine displaying the current date every second
166 for 5 seconds::
Victor Stinner7f314ed2014-10-15 18:49:16 +0200167
168 import asyncio
169 import datetime
170
Yury Selivanov02a0a192017-12-14 09:42:21 -0500171 async def display_date():
172 loop = asyncio.get_running_loop()
Yury Selivanov66f88282015-06-24 11:04:15 -0400173 end_time = loop.time() + 5.0
174 while True:
175 print(datetime.datetime.now())
176 if (loop.time() + 1.0) >= end_time:
177 break
178 await asyncio.sleep(1)
179
Yury Selivanov02a0a192017-12-14 09:42:21 -0500180 asyncio.run(display_date())
Yury Selivanov66f88282015-06-24 11:04:15 -0400181
Victor Stinner7f314ed2014-10-15 18:49:16 +0200182
Yury Selivanov512d7102018-09-17 19:35:30 -0400183Running Tasks Concurrently
184==========================
Victor Stinner7f314ed2014-10-15 18:49:16 +0200185
Yury Selivanov512d7102018-09-17 19:35:30 -0400186.. function:: gather(\*fs, loop=None, return_exceptions=False)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100187
Yury Selivanov512d7102018-09-17 19:35:30 -0400188 Return a Future aggregating results from the given coroutine objects,
189 Tasks, or Futures.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100190
Yury Selivanov512d7102018-09-17 19:35:30 -0400191 If all Tasks/Futures are completed successfully, the result is an
192 aggregate list of returned values. The result values are in the
193 order of the original *fs* sequence.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100194
Yury Selivanov512d7102018-09-17 19:35:30 -0400195 All coroutines in the *fs* list are automatically
196 scheduled as :class:`Tasks <Task>`.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100197
Yury Selivanov512d7102018-09-17 19:35:30 -0400198 If *return_exceptions* is ``True``, exceptions in the Tasks/Futures
199 are treated the same as successful results, and gathered in the
200 result list. Otherwise, the first raised exception is immediately
201 propagated to the returned Future.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100202
Yury Selivanov512d7102018-09-17 19:35:30 -0400203 If the outer Future is *cancelled*, all submitted Tasks/Futures
204 (that have not completed yet) are also *cancelled*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100205
Yury Selivanov512d7102018-09-17 19:35:30 -0400206 If any child is *cancelled*, it is treated as if it raised
207 :exc:`CancelledError` -- the outer Future is **not** cancelled in
208 this case. This is to prevent the cancellation of one submitted
209 Task/Future to cause other Tasks/Futures to be cancelled.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100210
Yury Selivanov512d7102018-09-17 19:35:30 -0400211 All futures must share the same event loop.
Victor Stinner83704962015-02-25 14:24:15 +0100212
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700213 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400214 If the *gather* itself is cancelled, the cancellation is
215 propagated regardless of *return_exceptions*.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700216
Yury Selivanov512d7102018-09-17 19:35:30 -0400217 .. _asyncio_example_gather:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
219 Example::
220
Yury Selivanov512d7102018-09-17 19:35:30 -0400221 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100222
Yury Selivanov512d7102018-09-17 19:35:30 -0400223 async def factorial(name, number):
224 f = 1
225 for i in range(2, number + 1):
226 print(f"Task {name}: Compute factorial({i})...")
227 await asyncio.sleep(1)
228 f *= i
229 print(f"Task {name}: factorial({number}) = {f}")
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov512d7102018-09-17 19:35:30 -0400231 async def main():
232 await asyncio.gather(
233 factorial("A", 2),
234 factorial("B", 3),
235 factorial("C", 4),
Miss Islington (bot)ee2ff1a2018-09-17 23:27:27 -0700236 )
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
Yury Selivanov512d7102018-09-17 19:35:30 -0400238 asyncio.run(main())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100239
Yury Selivanov512d7102018-09-17 19:35:30 -0400240 # Expected output:
241 #
242 # Task A: Compute factorial(2)...
243 # Task B: Compute factorial(2)...
244 # Task C: Compute factorial(2)...
245 # Task A: factorial(2) = 2
246 # Task B: Compute factorial(3)...
247 # Task C: Compute factorial(3)...
248 # Task B: factorial(3) = 6
249 # Task C: Compute factorial(4)...
250 # Task C: factorial(4) = 24
Victor Stinnerea3183f2013-12-03 01:08:00 +0100251
Victor Stinnerea3183f2013-12-03 01:08:00 +0100252
Yury Selivanov512d7102018-09-17 19:35:30 -0400253Shielding Tasks From Cancellation
254=================================
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400255
Yury Selivanov512d7102018-09-17 19:35:30 -0400256.. coroutinefunction:: shield(fut, \*, loop=None)
Yury Selivanove319ab02015-12-15 00:45:24 -0500257
Yury Selivanov512d7102018-09-17 19:35:30 -0400258 Wait for a Future/Task while protecting it from being cancelled.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200259
Yury Selivanov512d7102018-09-17 19:35:30 -0400260 *fut* can be a coroutine, a Task, or a Future-like object. If
261 *fut* is a coroutine it is automatically scheduled as a
262 :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100263
264 The statement::
265
Andrew Svetlov88743422017-12-11 17:35:49 +0200266 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100267
Yury Selivanov512d7102018-09-17 19:35:30 -0400268 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269
Andrew Svetlov88743422017-12-11 17:35:49 +0200270 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100271
Yury Selivanov512d7102018-09-17 19:35:30 -0400272 *except* that if the coroutine containing it is cancelled, the
273 Task running in ``something()`` is not cancelled. From the point
274 of view of ``something()``, the cancellation did not happen.
275 Although its caller is still cancelled, so the "await" expression
276 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
Yury Selivanov512d7102018-09-17 19:35:30 -0400278 If ``something()`` is cancelled by other means (i.e. from within
279 itself) that would also cancel ``shield()``.
280
281 If it is desired to completely ignore cancellation (not recommended)
282 the ``shield()`` function should be combined with a try/except
283 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100284
285 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200286 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287 except CancelledError:
288 res = None
289
Yury Selivanov950204d2016-05-16 16:23:00 -0400290
Yury Selivanov512d7102018-09-17 19:35:30 -0400291Timeouts
292========
293
294.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
295
296 Wait for a coroutine, Task, or Future to complete with timeout.
297
298 *fut* can be a coroutine, a Task, or a Future-like object. If
299 *fut* is a coroutine it is automatically scheduled as a
300 :class:`Task`.
301
302 *timeout* can either be ``None`` or a float or int number of seconds
303 to wait for. If *timeout* is ``None``, block until the future
304 completes.
305
306 If a timeout occurs, it cancels the task and raises
307 :exc:`asyncio.TimeoutError`.
308
309 To avoid the task cancellation, wrap it in :func:`shield`.
310
311 The function will wait until the future is actually cancelled,
312 so the total wait time may exceed the *timeout*.
313
314 If the wait is cancelled, the future *fut* is also cancelled.
315
316 .. _asyncio_example_waitfor:
317
318 Example::
319
320 async def eternity():
321 # Sleep for one hour
322 await asyncio.sleep(3600)
323 print('yay!')
324
325 async def main():
326 # Wait for at most 1 second
327 try:
328 await asyncio.wait_for(eternity(), timeout=1.0)
329 except asyncio.TimeoutError:
330 print('timeout!')
331
332 asyncio.run(main())
333
334 # Expected output:
335 #
336 # timeout!
337
338 .. versionchanged:: 3.7
339 When *fut* is cancelled due to a timeout, ``wait_for`` waits
340 for *fut* to be cancelled. Previously, it raised
341 :exc:`asyncio.TimeoutError` immediately.
342
343
344Waiting Primitives
345==================
346
347.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200348 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100349
Yury Selivanov512d7102018-09-17 19:35:30 -0400350 Wait for a set of coroutines, Tasks, or Futures to complete.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
Yury Selivanov512d7102018-09-17 19:35:30 -0400352 *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines
353 are automatically scheduled as :class:`Tasks <Task>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200354
Yury Selivanov512d7102018-09-17 19:35:30 -0400355 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
Yury Selivanov512d7102018-09-17 19:35:30 -0400357 *timeout* (a float or int), if specified, can be used to control
358 the maximum number of seconds to wait before returning.
359
360 Note that this function does not raise :exc:`asyncio.TimeoutError`.
361 Futures or Tasks that aren't done when the timeout occurs are simply
362 returned in the second set.
363
364 *return_when* indicates when this function should return. It must
365 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100366
367 .. tabularcolumns:: |l|L|
368
369 +-----------------------------+----------------------------------------+
370 | Constant | Description |
371 +=============================+========================================+
372 | :const:`FIRST_COMPLETED` | The function will return when any |
373 | | future finishes or is cancelled. |
374 +-----------------------------+----------------------------------------+
375 | :const:`FIRST_EXCEPTION` | The function will return when any |
376 | | future finishes by raising an |
377 | | exception. If no future raises an |
378 | | exception then it is equivalent to |
379 | | :const:`ALL_COMPLETED`. |
380 +-----------------------------+----------------------------------------+
381 | :const:`ALL_COMPLETED` | The function will return when all |
382 | | futures finish or are cancelled. |
383 +-----------------------------+----------------------------------------+
384
Yury Selivanov512d7102018-09-17 19:35:30 -0400385 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
386 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100387
388 Usage::
389
Andrew Svetlov88743422017-12-11 17:35:49 +0200390 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100391
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Yury Selivanov512d7102018-09-17 19:35:30 -0400393.. function:: as_completed(fs, \*, loop=None, timeout=None)
394
395 Return an iterator of awaitables which return
396 :class:`Future` instances.
397
398 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
399 all Futures are done.
400
401 Example::
402
403 for f in as_completed(fs):
404 result = await f
405 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
Victor Stinner3e09e322013-12-03 01:22:06 +0100407
Yury Selivanov512d7102018-09-17 19:35:30 -0400408Scheduling From Other Threads
409=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100410
Yury Selivanov512d7102018-09-17 19:35:30 -0400411.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100412
Yury Selivanov512d7102018-09-17 19:35:30 -0400413 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100414
Yury Selivanov512d7102018-09-17 19:35:30 -0400415 Return a :class:`concurrent.futures.Future` to access the result.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100416
Yury Selivanov512d7102018-09-17 19:35:30 -0400417 This function is meant to be called from a different OS thread
418 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200419
Yury Selivanov512d7102018-09-17 19:35:30 -0400420 # Create a coroutine
421 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500422
Yury Selivanov512d7102018-09-17 19:35:30 -0400423 # Submit the coroutine to a given loop
424 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100425
Yury Selivanov512d7102018-09-17 19:35:30 -0400426 # Wait for the result with an optional timeout argument
427 assert future.result(timeout) == 3
428
429 If an exception is raised in the coroutine, the returned Future
430 will be notified. It can also be used to cancel the task in
431 the event loop::
432
433 try:
434 result = future.result(timeout)
435 except asyncio.TimeoutError:
436 print('The coroutine took too long, cancelling the task...')
437 future.cancel()
438 except Exception as exc:
439 print('The coroutine raised an exception: {!r}'.format(exc))
440 else:
441 print('The coroutine returned: {!r}'.format(result))
442
443 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
444 section of the documentation.
445
446 Unlike other asyncio functions this functions requires the *loop*
447 argument to be passed explicitly.
448
449 .. versionadded:: 3.5.1
450
451
452Introspection
453=============
454
455
456.. function:: current_task(loop=None)
457
458 Return the currently running :class:`Task` instance, or ``None`` if
459 no task is running.
460
461 If *loop* is ``None`` :func:`get_running_loop` is used to get
462 the current loop.
463
464 .. versionadded:: 3.7
465
466
467.. function:: all_tasks(loop=None)
468
469 Return a set of not yet finished :class:`Task` objects run by
470 the loop.
471
472 If *loop* is ``None``, :func:`get_running_loop` is used for getting
473 current loop.
474
475 .. versionadded:: 3.7
476
477
478Task Object
479===========
480
481.. class:: Task(coro, \*, loop=None)
482
483 A :class:`Future`-like object that wraps a Python
484 :ref:`coroutine <coroutine>`. Not thread-safe.
485
486 Tasks are used to run coroutines in event loops.
487 If a coroutine awaits on a Future, the Task suspends
488 the execution of the coroutine and waits for the completion
489 of the Future. When the Future is *done*, the execution of
490 the wrapped coroutine resumes.
491
492 Event loops use cooperative scheduling: an event loop runs
493 one Task at a time. While a Task awaits for the completion of a
494 Future, the event loop runs other Tasks, callbacks, or performs
495 IO operations.
496
497 Use the high-level :func:`asyncio.create_task` function to create
498 Tasks, or the low-level :meth:`loop.create_task` or
499 :func:`ensure_future` functions. Manual instantiation of Tasks
500 is discouraged.
501
502 To cancel a running Task use the :meth:`cancel` method. Calling it
503 will cause the Task to throw a :exc:`CancelledError` exception into
504 the wrapped coroutine. If a coroutine is awaiting on a Future
505 object during cancellation, the Future object will be cancelled.
506
507 :meth:`cancelled` can be used to check if the Task was cancelled.
508 The method returns ``True`` if the wrapped coroutine did not
509 suppress the :exc:`CancelledError` exception and was actually
510 cancelled.
511
512 :class:`asyncio.Task` inherits from :class:`Future` all of its
513 APIs except :meth:`Future.set_result` and
514 :meth:`Future.set_exception`.
515
516 Tasks support the :mod:`contextvars` module. When a Task
517 is created it copies the current context and later runs its
518 coroutine in the copied context.
Miss Islington (bot)d8948c52018-05-29 15:37:06 -0700519
520 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400521 Added support for the :mod:`contextvars` module.
522
523 .. method:: cancel()
524
525 Request the Task to be cancelled.
526
527 This arranges for a :exc:`CancelledError` exception to be thrown
528 into the wrapped coroutine on the next cycle of the event loop.
529
530 The coroutine then has a chance to clean up or even deny the
531 request by suppressing the exception with a :keyword:`try` ...
532 ... ``except CancelledError`` ... :keyword:`finally` block.
533 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
534 not guarantee that the Task will be cancelled, although
535 suppressing cancellation completely is not common and is actively
536 discouraged.
537
538 .. _asyncio_example_task_cancel:
539
540 The following example illustrates how coroutines can intercept
541 the cancellation request::
542
543 async def cancel_me():
544 print('cancel_me(): before sleep')
545
546 try:
547 # Wait for 1 hour
548 await asyncio.sleep(3600)
549 except asyncio.CancelledError:
550 print('cancel_me(): cancel sleep')
551 raise
552 finally:
553 print('cancel_me(): after sleep')
554
555 async def main():
556 # Create a "cancel_me" Task
557 task = asyncio.create_task(cancel_me())
558
559 # Wait for 1 second
560 await asyncio.sleep(1)
561
562 task.cancel()
563 try:
564 await task
565 except asyncio.CancelledError:
566 print("main(): cancel_me is cancelled now")
567
568 asyncio.run(main())
569
570 # Expected output:
571 #
572 # cancel_me(): before sleep
573 # cancel_me(): cancel sleep
574 # cancel_me(): after sleep
575 # main(): cancel_me is cancelled now
576
577 .. method:: cancelled()
578
579 Return ``True`` if the Task is *cancelled*.
580
581 The Task is *cancelled* when the cancellation was requested with
582 :meth:`cancel` and the wrapped coroutine propagated the
583 :exc:`CancelledError` exception thrown into it.
584
585 .. method:: done()
586
587 Return ``True`` if the Task is *done*.
588
589 A Task is *done* when the wrapped coroutine either returned
590 a value, raised an exception, or the Task was cancelled.
591
592 .. method:: get_stack(\*, limit=None)
593
594 Return the list of stack frames for this Task.
595
596 If the wrapped coroutine is not done, this returns the stack
597 where it is suspended. If the coroutine has completed
598 successfully or was cancelled, this returns an empty list.
599 If the coroutine was terminated by an exception, this returns
600 the list of traceback frames.
601
602 The frames are always ordered from oldest to newest.
603
604 Only one stack frame is returned for a suspended coroutine.
605
606 The optional *limit* argument sets the maximum number of frames
607 to return; by default all available frames are returned.
608 The ordering of the returned list differs depending on whether
609 a stack or a traceback is returned: the newest frames of a
610 stack are returned, but the oldest frames of a traceback are
611 returned. (This matches the behavior of the traceback module.)
612
613 .. method:: print_stack(\*, limit=None, file=None)
614
615 Print the stack or traceback for this Task.
616
617 This produces output similar to that of the traceback module
618 for the frames retrieved by :meth:`get_stack`.
619
620 The *limit* argument is passed to :meth:`get_stack` directly.
621
622 The *file* argument is an I/O stream to which the output
623 is written; by default output is written to :data:`sys.stderr`.
624
625 .. classmethod:: all_tasks(loop=None)
626
627 Return a set of all tasks for an event loop.
628
629 By default all tasks for the current event loop are returned.
630 If *loop* is ``None``, the :func:`get_event_loop` function
631 is used to get the current loop.
632
633 This method is **deprecated** and will be removed in
634 Python 3.9. Use the :func:`all_tasks` function instead.
635
636 .. classmethod:: current_task(loop=None)
637
638 Return the currently running task or ``None``.
639
640 If *loop* is ``None``, the :func:`get_event_loop` function
641 is used to get the current loop.
642
643 This method is **deprecated** and will be removed in
644 Python 3.9. Use the :func:`current_task` function instead.
645
646
647.. _asyncio_generator_based_coro:
648
649Generator-based Coroutines
650==========================
651
652.. note::
653
654 Support for generator-based coroutines is **deprecated** and
655 is scheduled for removal in Python 4.0.
656
657Generator-based coroutines predate async/await syntax. They are
658Python generators that use ``yield from`` expressions to await
659on Futures and other coroutines.
660
661Generator-based coroutines should be decorated with
662:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
663enforced.
664
665
666.. decorator:: coroutine
667
668 Decorator to mark generator-based coroutines.
669
670 This decorator enables legacy generator-based coroutines to be
671 compatible with async/await code::
672
673 @asyncio.coroutine
674 def old_style_coroutine():
675 yield from asyncio.sleep(1)
676
677 async def main():
678 await old_style_coroutine()
679
680 This decorator is **deprecated** and is scheduled for removal in
681 Python 4.0.
682
683 This decorator should not be used for :keyword:`async def`
684 coroutines.
685
686.. function:: iscoroutine(obj)
687
688 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
689
690 This method is different from :func:`inspect.iscoroutine` because
691 it returns ``True`` for generator-based coroutines decorated with
692 :func:`@coroutine <coroutine>`.
693
694.. function:: iscoroutinefunction(func)
695
696 Return ``True`` if *func* is a :ref:`coroutine function
697 <coroutine>`.
698
699 This method is different from :func:`inspect.iscoroutinefunction`
700 because it returns ``True`` for generator-based coroutine functions
701 decorated with :func:`@coroutine <coroutine>`.