blob: 4f37296f4a3ed1a0080552a2ea44c13e3523a55f [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov3faaa882018-09-14 13:32:07 -07003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov3faaa882018-09-14 13:32:07 -07008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov3faaa882018-09-14 13:32:07 -070011.. contents::
12 :depth: 1
13 :local:
14
lf627d2c82017-07-25 17:03:51 -060015
Victor Stinnerea3183f2013-12-03 01:08:00 +010016.. _coroutine:
17
18Coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov3faaa882018-09-14 13:32:07 -070021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Yury Selivanovb042cf12018-09-18 02:47:54 -040023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov3faaa882018-09-14 13:32:07 -070026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov3faaa882018-09-14 13:32:07 -070028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov3faaa882018-09-14 13:32:07 -070033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov3faaa882018-09-14 13:32:07 -070037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov3faaa882018-09-14 13:32:07 -070040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov3faaa882018-09-14 13:32:07 -070043To 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():
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
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
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 Selivanov3faaa882018-09-14 13:32:07 -0700115Running an asyncio Program
116==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100117
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -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 Selivanov3faaa882018-09-14 13:32:07 -0700127 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -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 Selivanov3faaa882018-09-14 13:32:07 -0700138Creating Tasks
139==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100140
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300141.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200142
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400143 Wrap the *coro* :ref:`coroutine <coroutine>` into a task and schedule
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300144 its execution. Return the task object.
145
146 If *name* is not ``None``, it is set as the name of the task using
147 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200148
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400149 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200150 :exc:`RuntimeError` is raised if there is no running loop in
151 current thread.
152
153 .. versionadded:: 3.7
154
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300155 .. versionchanged:: 3.8
156 Added the ``name`` parameter.
157
Victor Stinnerea3183f2013-12-03 01:08:00 +0100158
Yury Selivanov3faaa882018-09-14 13:32:07 -0700159Sleeping
160========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200161
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100162.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100163
Yury Selivanov3faaa882018-09-14 13:32:07 -0700164 Block for *delay* seconds.
165
166 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800167 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700169 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100170
Yury Selivanov3faaa882018-09-14 13:32:07 -0700171 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400172 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100173
Yury Selivanov3faaa882018-09-14 13:32:07 -0700174 import asyncio
175 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100176
Yury Selivanov3faaa882018-09-14 13:32:07 -0700177 async def display_date():
178 loop = asyncio.get_running_loop()
179 end_time = loop.time() + 5.0
180 while True:
181 print(datetime.datetime.now())
182 if (loop.time() + 1.0) >= end_time:
183 break
184 await asyncio.sleep(1)
185
186 asyncio.run(display_date())
187
188
189Running Tasks Concurrently
190==========================
191
Yury Selivanov394374e2018-09-17 15:35:24 -0400192.. function:: gather(\*fs, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700193
194 Return a Future aggregating results from the given coroutine objects,
195 Tasks, or Futures.
196
197 If all Tasks/Futures are completed successfully, the result is an
198 aggregate list of returned values. The result values are in the
199 order of the original *fs* sequence.
200
201 All coroutines in the *fs* list are automatically
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400202 scheduled as :class:`Tasks <Task>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700203
204 If *return_exceptions* is ``True``, exceptions in the Tasks/Futures
205 are treated the same as successful results, and gathered in the
206 result list. Otherwise, the first raised exception is immediately
207 propagated to the returned Future.
208
209 If the outer Future is *cancelled*, all submitted Tasks/Futures
210 (that have not completed yet) are also *cancelled*.
211
212 If any child is *cancelled*, it is treated as if it raised
213 :exc:`CancelledError` -- the outer Future is **not** cancelled in
214 this case. This is to prevent the cancellation of one submitted
215 Task/Future to cause other Tasks/Futures to be cancelled.
216
217 All futures must share the same event loop.
218
219 .. versionchanged:: 3.7
220 If the *gather* itself is cancelled, the cancellation is
221 propagated regardless of *return_exceptions*.
222
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700223 .. _asyncio_example_gather:
224
Yury Selivanov3faaa882018-09-14 13:32:07 -0700225 Example::
226
227 import asyncio
228
229 async def factorial(name, number):
230 f = 1
231 for i in range(2, number + 1):
232 print(f"Task {name}: Compute factorial({i})...")
233 await asyncio.sleep(1)
234 f *= i
235 print(f"Task {name}: factorial({number}) = {f}")
236
237 async def main():
238 await asyncio.gather(
239 factorial("A", 2),
240 factorial("B", 3),
241 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200242 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700243
244 asyncio.run(main())
245
246 # Expected output:
247 #
248 # Task A: Compute factorial(2)...
249 # Task B: Compute factorial(2)...
250 # Task C: Compute factorial(2)...
251 # Task A: factorial(2) = 2
252 # Task B: Compute factorial(3)...
253 # Task C: Compute factorial(3)...
254 # Task B: factorial(3) = 6
255 # Task C: Compute factorial(4)...
256 # Task C: factorial(4) = 24
257
258
259Shielding Tasks From Cancellation
260=================================
261
262.. coroutinefunction:: shield(fut, \*, loop=None)
263
264 Wait for a Future/Task while protecting it from being cancelled.
265
266 *fut* can be a coroutine, a Task, or a Future-like object. If
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400267 *fut* is a coroutine it is automatically scheduled as a
Yury Selivanov3faaa882018-09-14 13:32:07 -0700268 :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269
270 The statement::
271
Andrew Svetlov88743422017-12-11 17:35:49 +0200272 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100273
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400274 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100275
Andrew Svetlov88743422017-12-11 17:35:49 +0200276 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
Yury Selivanov3faaa882018-09-14 13:32:07 -0700278 *except* that if the coroutine containing it is cancelled, the
279 Task running in ``something()`` is not cancelled. From the point
280 of view of ``something()``, the cancellation did not happen.
281 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400282 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
Yury Selivanov3faaa882018-09-14 13:32:07 -0700284 If ``something()`` is cancelled by other means (i.e. from within
285 itself) that would also cancel ``shield()``.
286
287 If it is desired to completely ignore cancellation (not recommended)
288 the ``shield()`` function should be combined with a try/except
289 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100290
291 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200292 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100293 except CancelledError:
294 res = None
295
Yury Selivanov950204d2016-05-16 16:23:00 -0400296
Yury Selivanov3faaa882018-09-14 13:32:07 -0700297Timeouts
298========
299
300.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
301
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400302 Wait for a coroutine, Task, or Future to complete with timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700303
304 *fut* can be a coroutine, a Task, or a Future-like object. If
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400305 *fut* is a coroutine it is automatically scheduled as a
Yury Selivanov3faaa882018-09-14 13:32:07 -0700306 :class:`Task`.
307
308 *timeout* can either be ``None`` or a float or int number of seconds
309 to wait for. If *timeout* is ``None``, block until the future
310 completes.
311
312 If a timeout occurs, it cancels the task and raises
313 :exc:`asyncio.TimeoutError`.
314
315 To avoid the task cancellation, wrap it in :func:`shield`.
316
317 The function will wait until the future is actually cancelled,
318 so the total wait time may exceed the *timeout*.
319
320 If the wait is cancelled, the future *fut* is also cancelled.
321
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700322 .. _asyncio_example_waitfor:
323
Yury Selivanov3faaa882018-09-14 13:32:07 -0700324 Example::
325
326 async def eternity():
327 # Sleep for one hour
328 await asyncio.sleep(3600)
329 print('yay!')
330
331 async def main():
332 # Wait for at most 1 second
333 try:
334 await asyncio.wait_for(eternity(), timeout=1.0)
335 except asyncio.TimeoutError:
336 print('timeout!')
337
338 asyncio.run(main())
339
340 # Expected output:
341 #
342 # timeout!
343
344 .. versionchanged:: 3.7
345 When *fut* is cancelled due to a timeout, ``wait_for`` waits
346 for *fut* to be cancelled. Previously, it raised
347 :exc:`asyncio.TimeoutError` immediately.
348
349
350Waiting Primitives
351==================
352
353.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200354 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100355
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400356 Wait for a set of coroutines, Tasks, or Futures to complete.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100357
Yury Selivanov3faaa882018-09-14 13:32:07 -0700358 *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400359 are automatically scheduled as :class:`Tasks <Task>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200360
Yury Selivanov3faaa882018-09-14 13:32:07 -0700361 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
Yury Selivanov3faaa882018-09-14 13:32:07 -0700363 *timeout* (a float or int), if specified, can be used to control
364 the maximum number of seconds to wait before returning.
365
366 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400367 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700368 returned in the second set.
369
370 *return_when* indicates when this function should return. It must
371 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100372
373 .. tabularcolumns:: |l|L|
374
375 +-----------------------------+----------------------------------------+
376 | Constant | Description |
377 +=============================+========================================+
378 | :const:`FIRST_COMPLETED` | The function will return when any |
379 | | future finishes or is cancelled. |
380 +-----------------------------+----------------------------------------+
381 | :const:`FIRST_EXCEPTION` | The function will return when any |
382 | | future finishes by raising an |
383 | | exception. If no future raises an |
384 | | exception then it is equivalent to |
385 | | :const:`ALL_COMPLETED`. |
386 +-----------------------------+----------------------------------------+
387 | :const:`ALL_COMPLETED` | The function will return when all |
388 | | futures finish or are cancelled. |
389 +-----------------------------+----------------------------------------+
390
Yury Selivanov3faaa882018-09-14 13:32:07 -0700391 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
392 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393
394 Usage::
395
Andrew Svetlov88743422017-12-11 17:35:49 +0200396 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100397
Victor Stinnerea3183f2013-12-03 01:08:00 +0100398
Yury Selivanov3faaa882018-09-14 13:32:07 -0700399.. function:: as_completed(fs, \*, loop=None, timeout=None)
400
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400401 Return an iterator of awaitables which return
Yury Selivanov3faaa882018-09-14 13:32:07 -0700402 :class:`Future` instances.
403
404 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
405 all Futures are done.
406
407 Example::
408
409 for f in as_completed(fs):
410 result = await f
411 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412
Victor Stinner3e09e322013-12-03 01:22:06 +0100413
Yury Selivanov3faaa882018-09-14 13:32:07 -0700414Scheduling From Other Threads
415=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100416
Yury Selivanov3faaa882018-09-14 13:32:07 -0700417.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100418
Yury Selivanov3faaa882018-09-14 13:32:07 -0700419 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100420
Yury Selivanov3faaa882018-09-14 13:32:07 -0700421 Return a :class:`concurrent.futures.Future` to access the result.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100422
Yury Selivanov3faaa882018-09-14 13:32:07 -0700423 This function is meant to be called from a different OS thread
424 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200425
Yury Selivanov3faaa882018-09-14 13:32:07 -0700426 # Create a coroutine
427 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500428
Yury Selivanov3faaa882018-09-14 13:32:07 -0700429 # Submit the coroutine to a given loop
430 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100431
Yury Selivanov3faaa882018-09-14 13:32:07 -0700432 # Wait for the result with an optional timeout argument
433 assert future.result(timeout) == 3
434
435 If an exception is raised in the coroutine, the returned Future
436 will be notified. It can also be used to cancel the task in
437 the event loop::
438
439 try:
440 result = future.result(timeout)
441 except asyncio.TimeoutError:
442 print('The coroutine took too long, cancelling the task...')
443 future.cancel()
444 except Exception as exc:
445 print('The coroutine raised an exception: {!r}'.format(exc))
446 else:
447 print('The coroutine returned: {!r}'.format(result))
448
449 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
450 section of the documentation.
451
452 Unlike other asyncio functions this functions requires the *loop*
453 argument to be passed explicitly.
454
455 .. versionadded:: 3.5.1
456
457
458Introspection
459=============
460
461
462.. function:: current_task(loop=None)
463
464 Return the currently running :class:`Task` instance, or ``None`` if
465 no task is running.
466
467 If *loop* is ``None`` :func:`get_running_loop` is used to get
468 the current loop.
469
470 .. versionadded:: 3.7
471
472
473.. function:: all_tasks(loop=None)
474
475 Return a set of not yet finished :class:`Task` objects run by
476 the loop.
477
478 If *loop* is ``None``, :func:`get_running_loop` is used for getting
479 current loop.
480
481 .. versionadded:: 3.7
482
483
484Task Object
485===========
486
487.. class:: Task(coro, \*, loop=None, name=None)
488
489 A :class:`Future`-like object that wraps a Python
490 :ref:`coroutine <coroutine>`. Not thread-safe.
491
492 Tasks are used to run coroutines in event loops.
493 If a coroutine awaits on a Future, the Task suspends
494 the execution of the coroutine and waits for the completion
495 of the Future. When the Future is *done*, the execution of
496 the wrapped coroutine resumes.
497
498 Event loops use cooperative scheduling: an event loop runs
499 one Task at a time. While a Task awaits for the completion of a
500 Future, the event loop runs other Tasks, callbacks, or performs
501 IO operations.
502
503 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400504 Tasks, or the low-level :meth:`loop.create_task` or
505 :func:`ensure_future` functions. Manual instantiation of Tasks
506 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700507
508 To cancel a running Task use the :meth:`cancel` method. Calling it
509 will cause the Task to throw a :exc:`CancelledError` exception into
510 the wrapped coroutine. If a coroutine is awaiting on a Future
511 object during cancellation, the Future object will be cancelled.
512
513 :meth:`cancelled` can be used to check if the Task was cancelled.
514 The method returns ``True`` if the wrapped coroutine did not
515 suppress the :exc:`CancelledError` exception and was actually
516 cancelled.
517
518 :class:`asyncio.Task` inherits from :class:`Future` all of its
519 APIs except :meth:`Future.set_result` and
520 :meth:`Future.set_exception`.
521
522 Tasks support the :mod:`contextvars` module. When a Task
523 is created it copies the current context and later runs its
524 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400525
526 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700527 Added support for the :mod:`contextvars` module.
528
529 .. versionchanged:: 3.8
530 Added the ``name`` parameter.
531
532 .. method:: cancel()
533
534 Request the Task to be cancelled.
535
536 This arranges for a :exc:`CancelledError` exception to be thrown
537 into the wrapped coroutine on the next cycle of the event loop.
538
539 The coroutine then has a chance to clean up or even deny the
540 request by suppressing the exception with a :keyword:`try` ...
541 ... ``except CancelledError`` ... :keyword:`finally` block.
542 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
543 not guarantee that the Task will be cancelled, although
544 suppressing cancellation completely is not common and is actively
545 discouraged.
546
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700547 .. _asyncio_example_task_cancel:
548
Yury Selivanov3faaa882018-09-14 13:32:07 -0700549 The following example illustrates how coroutines can intercept
550 the cancellation request::
551
552 async def cancel_me():
553 print('cancel_me(): before sleep')
554
555 try:
556 # Wait for 1 hour
557 await asyncio.sleep(3600)
558 except asyncio.CancelledError:
559 print('cancel_me(): cancel sleep')
560 raise
561 finally:
562 print('cancel_me(): after sleep')
563
564 async def main():
565 # Create a "cancel_me" Task
566 task = asyncio.create_task(cancel_me())
567
568 # Wait for 1 second
569 await asyncio.sleep(1)
570
571 task.cancel()
572 try:
573 await task
574 except asyncio.CancelledError:
575 print("main(): cancel_me is cancelled now")
576
577 asyncio.run(main())
578
579 # Expected output:
580 #
581 # cancel_me(): before sleep
582 # cancel_me(): cancel sleep
583 # cancel_me(): after sleep
584 # main(): cancel_me is cancelled now
585
586 .. method:: cancelled()
587
588 Return ``True`` if the Task is *cancelled*.
589
590 The Task is *cancelled* when the cancellation was requested with
591 :meth:`cancel` and the wrapped coroutine propagated the
592 :exc:`CancelledError` exception thrown into it.
593
594 .. method:: done()
595
596 Return ``True`` if the Task is *done*.
597
598 A Task is *done* when the wrapped coroutine either returned
599 a value, raised an exception, or the Task was cancelled.
600
601 .. method:: get_stack(\*, limit=None)
602
603 Return the list of stack frames for this Task.
604
605 If the wrapped coroutine is not done, this returns the stack
606 where it is suspended. If the coroutine has completed
607 successfully or was cancelled, this returns an empty list.
608 If the coroutine was terminated by an exception, this returns
609 the list of traceback frames.
610
611 The frames are always ordered from oldest to newest.
612
613 Only one stack frame is returned for a suspended coroutine.
614
615 The optional *limit* argument sets the maximum number of frames
616 to return; by default all available frames are returned.
617 The ordering of the returned list differs depending on whether
618 a stack or a traceback is returned: the newest frames of a
619 stack are returned, but the oldest frames of a traceback are
620 returned. (This matches the behavior of the traceback module.)
621
622 .. method:: print_stack(\*, limit=None, file=None)
623
624 Print the stack or traceback for this Task.
625
626 This produces output similar to that of the traceback module
627 for the frames retrieved by :meth:`get_stack`.
628
629 The *limit* argument is passed to :meth:`get_stack` directly.
630
631 The *file* argument is an I/O stream to which the output
632 is written; by default output is written to :data:`sys.stderr`.
633
634 .. method:: get_name()
635
636 Return the name of the Task.
637
638 If no name has been explicitly assigned to the Task, the default
639 asyncio Task implementation generates a default name during
640 instantiation.
641
642 .. versionadded:: 3.8
643
644 .. method:: set_name(value)
645
646 Set the name of the Task.
647
648 The *value* argument can be any object, which is then
649 converted to a string.
650
651 In the default Task implementation, the name will be visible
652 in the :func:`repr` output of a task object.
653
654 .. versionadded:: 3.8
655
656 .. classmethod:: all_tasks(loop=None)
657
658 Return a set of all tasks for an event loop.
659
660 By default all tasks for the current event loop are returned.
661 If *loop* is ``None``, the :func:`get_event_loop` function
662 is used to get the current loop.
663
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400664 This method is **deprecated** and will be removed in
Yury Selivanov3faaa882018-09-14 13:32:07 -0700665 Python 3.9. Use the :func:`all_tasks` function instead.
666
667 .. classmethod:: current_task(loop=None)
668
669 Return the currently running task or ``None``.
670
671 If *loop* is ``None``, the :func:`get_event_loop` function
672 is used to get the current loop.
673
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400674 This method is **deprecated** and will be removed in
Yury Selivanov3faaa882018-09-14 13:32:07 -0700675 Python 3.9. Use the :func:`current_task` function instead.
676
677
678.. _asyncio_generator_based_coro:
679
680Generator-based Coroutines
681==========================
682
683.. note::
684
685 Support for generator-based coroutines is **deprecated** and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400686 is scheduled for removal in Python 4.0.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700687
688Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400689Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700690on Futures and other coroutines.
691
692Generator-based coroutines should be decorated with
693:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
694enforced.
695
696
697.. decorator:: coroutine
698
699 Decorator to mark generator-based coroutines.
700
701 This decorator enables legacy generator-based coroutines to be
702 compatible with async/await code::
703
704 @asyncio.coroutine
705 def old_style_coroutine():
706 yield from asyncio.sleep(1)
707
708 async def main():
709 await old_style_coroutine()
710
711 This decorator is **deprecated** and is scheduled for removal in
712 Python 4.0.
713
714 This decorator should not be used for :keyword:`async def`
715 coroutines.
716
717.. function:: iscoroutine(obj)
718
719 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
720
721 This method is different from :func:`inspect.iscoroutine` because
722 it returns ``True`` for generator-based coroutines decorated with
723 :func:`@coroutine <coroutine>`.
724
725.. function:: iscoroutinefunction(func)
726
727 Return ``True`` if *func* is a :ref:`coroutine function
728 <coroutine>`.
729
730 This method is different from :func:`inspect.iscoroutinefunction`
731 because it returns ``True`` for generator-based coroutine functions
732 decorated with :func:`@coroutine <coroutine>`.