blob: 3faaf0cdb9b8dfb090e6e52aac90173e61255dad [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
23of code prints "hello", waits 1 second, and prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
Yury Selivanov3faaa882018-09-14 13:32:07 -070025 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010026
Yury Selivanov3faaa882018-09-14 13:32:07 -070027 >>> async def main():
28 ... print('hello')
29 ... await asyncio.sleep(1)
30 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
Yury Selivanov3faaa882018-09-14 13:32:07 -070032 >>> asyncio.run(main())
33 hello
34 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Yury Selivanov3faaa882018-09-14 13:32:07 -070036Note that simply calling a coroutine will not schedule it to
37be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010038
Yury Selivanov3faaa882018-09-14 13:32:07 -070039 >>> main()
40 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010041
Yury Selivanov3faaa882018-09-14 13:32:07 -070042To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010043
Yury Selivanov3faaa882018-09-14 13:32:07 -070044* By using 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 Selivanov3faaa882018-09-14 13:32:07 -070047* By 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 Selivanov3faaa882018-09-14 13:32:07 -070051 import asyncio
52 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Yury Selivanov3faaa882018-09-14 13:32:07 -070054 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* By using the :func:`asyncio.create_task` function to run coroutines
76 concurrently as asyncio :class:`Tasks <Task>`.
77
78 Let's modify the above example and run two "set_after" coroutines
79 *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 Selivanov3faaa882018-09-14 13:32:07 -0700114Running an asyncio Program
115==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -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 Selivanov3faaa882018-09-14 13:32:07 -0700126 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 Selivanov394374e2018-09-17 15:35:24 -0400133 **Important:** this has been added to asyncio in Python 3.7
Yury Selivanovd8d715f2018-05-17 13:44:00 -0400134 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500135
136
Yury Selivanov3faaa882018-09-14 13:32:07 -0700137Creating Tasks
138==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300140.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200141
142 Wrap a :ref:`coroutine <coroutine>` *coro* into a task and schedule
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300143 its execution. Return the task object.
144
145 If *name* is not ``None``, it is set as the name of the task using
146 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200147
148 The task is executed in :func:`get_running_loop` context,
149 :exc:`RuntimeError` is raised if there is no running loop in
150 current thread.
151
152 .. versionadded:: 3.7
153
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300154 .. versionchanged:: 3.8
155 Added the ``name`` parameter.
156
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157
Yury Selivanov3faaa882018-09-14 13:32:07 -0700158Sleeping
159========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200160
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100161.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100162
Yury Selivanov3faaa882018-09-14 13:32:07 -0700163 Block for *delay* seconds.
164
165 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800166 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100167
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700168 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100169
Yury Selivanov3faaa882018-09-14 13:32:07 -0700170 Example of coroutine displaying the current date every second
171 during 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100172
Yury Selivanov3faaa882018-09-14 13:32:07 -0700173 import asyncio
174 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100175
Yury Selivanov3faaa882018-09-14 13:32:07 -0700176 async def display_date():
177 loop = asyncio.get_running_loop()
178 end_time = loop.time() + 5.0
179 while True:
180 print(datetime.datetime.now())
181 if (loop.time() + 1.0) >= end_time:
182 break
183 await asyncio.sleep(1)
184
185 asyncio.run(display_date())
186
187
188Running Tasks Concurrently
189==========================
190
Yury Selivanov394374e2018-09-17 15:35:24 -0400191.. function:: gather(\*fs, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700192
193 Return a Future aggregating results from the given coroutine objects,
194 Tasks, or Futures.
195
196 If all Tasks/Futures are completed successfully, the result is an
197 aggregate list of returned values. The result values are in the
198 order of the original *fs* sequence.
199
200 All coroutines in the *fs* list are automatically
201 wrapped in :class:`Tasks <Task>`.
202
203 If *return_exceptions* is ``True``, exceptions in the Tasks/Futures
204 are treated the same as successful results, and gathered in the
205 result list. Otherwise, the first raised exception is immediately
206 propagated to the returned Future.
207
208 If the outer Future is *cancelled*, all submitted Tasks/Futures
209 (that have not completed yet) are also *cancelled*.
210
211 If any child is *cancelled*, it is treated as if it raised
212 :exc:`CancelledError` -- the outer Future is **not** cancelled in
213 this case. This is to prevent the cancellation of one submitted
214 Task/Future to cause other Tasks/Futures to be cancelled.
215
216 All futures must share the same event loop.
217
218 .. versionchanged:: 3.7
219 If the *gather* itself is cancelled, the cancellation is
220 propagated regardless of *return_exceptions*.
221
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700222 .. _asyncio_example_gather:
223
Yury Selivanov3faaa882018-09-14 13:32:07 -0700224 Example::
225
226 import asyncio
227
228 async def factorial(name, number):
229 f = 1
230 for i in range(2, number + 1):
231 print(f"Task {name}: Compute factorial({i})...")
232 await asyncio.sleep(1)
233 f *= i
234 print(f"Task {name}: factorial({number}) = {f}")
235
236 async def main():
237 await asyncio.gather(
238 factorial("A", 2),
239 factorial("B", 3),
240 factorial("C", 4),
241 ))
242
243 asyncio.run(main())
244
245 # Expected output:
246 #
247 # Task A: Compute factorial(2)...
248 # Task B: Compute factorial(2)...
249 # Task C: Compute factorial(2)...
250 # Task A: factorial(2) = 2
251 # Task B: Compute factorial(3)...
252 # Task C: Compute factorial(3)...
253 # Task B: factorial(3) = 6
254 # Task C: Compute factorial(4)...
255 # Task C: factorial(4) = 24
256
257
258Shielding Tasks From Cancellation
259=================================
260
261.. coroutinefunction:: shield(fut, \*, loop=None)
262
263 Wait for a Future/Task while protecting it from being cancelled.
264
265 *fut* can be a coroutine, a Task, or a Future-like object. If
266 *fut* is a coroutine it is automatically wrapped in a
267 :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
269 The statement::
270
Andrew Svetlov88743422017-12-11 17:35:49 +0200271 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100272
Yury Selivanov3faaa882018-09-14 13:32:07 -0700273 is equivalent to the statement::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274
Andrew Svetlov88743422017-12-11 17:35:49 +0200275 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100276
Yury Selivanov3faaa882018-09-14 13:32:07 -0700277 *except* that if the coroutine containing it is cancelled, the
278 Task running in ``something()`` is not cancelled. From the point
279 of view of ``something()``, the cancellation did not happen.
280 Although its caller is still cancelled, so the "await" expression
281 still raises :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100282
Yury Selivanov3faaa882018-09-14 13:32:07 -0700283 If ``something()`` is cancelled by other means (i.e. from within
284 itself) that would also cancel ``shield()``.
285
286 If it is desired to completely ignore cancellation (not recommended)
287 the ``shield()`` function should be combined with a try/except
288 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100289
290 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200291 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292 except CancelledError:
293 res = None
294
Yury Selivanov950204d2016-05-16 16:23:00 -0400295
Yury Selivanov3faaa882018-09-14 13:32:07 -0700296Timeouts
297========
298
299.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
300
301 Wait for the coroutine, Task, or Future to complete with timeout.
302
303 *fut* can be a coroutine, a Task, or a Future-like object. If
304 *fut* is a coroutine it is automatically wrapped in a
305 :class:`Task`.
306
307 *timeout* can either be ``None`` or a float or int number of seconds
308 to wait for. If *timeout* is ``None``, block until the future
309 completes.
310
311 If a timeout occurs, it cancels the task and raises
312 :exc:`asyncio.TimeoutError`.
313
314 To avoid the task cancellation, wrap it in :func:`shield`.
315
316 The function will wait until the future is actually cancelled,
317 so the total wait time may exceed the *timeout*.
318
319 If the wait is cancelled, the future *fut* is also cancelled.
320
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700321 .. _asyncio_example_waitfor:
322
Yury Selivanov3faaa882018-09-14 13:32:07 -0700323 Example::
324
325 async def eternity():
326 # Sleep for one hour
327 await asyncio.sleep(3600)
328 print('yay!')
329
330 async def main():
331 # Wait for at most 1 second
332 try:
333 await asyncio.wait_for(eternity(), timeout=1.0)
334 except asyncio.TimeoutError:
335 print('timeout!')
336
337 asyncio.run(main())
338
339 # Expected output:
340 #
341 # timeout!
342
343 .. versionchanged:: 3.7
344 When *fut* is cancelled due to a timeout, ``wait_for`` waits
345 for *fut* to be cancelled. Previously, it raised
346 :exc:`asyncio.TimeoutError` immediately.
347
348
349Waiting Primitives
350==================
351
352.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200353 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100354
Yury Selivanov3faaa882018-09-14 13:32:07 -0700355 Wait for a set of Futures to complete.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
Yury Selivanov3faaa882018-09-14 13:32:07 -0700357 *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines
358 are automatically wrapped in :class:`Tasks <Task>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200359
Yury Selivanov3faaa882018-09-14 13:32:07 -0700360 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100361
Yury Selivanov3faaa882018-09-14 13:32:07 -0700362 *timeout* (a float or int), if specified, can be used to control
363 the maximum number of seconds to wait before returning.
364
365 Note that this function does not raise :exc:`asyncio.TimeoutError`.
366 Futures or Tasks that aren't done when the timeout occurs are just
367 returned in the second set.
368
369 *return_when* indicates when this function should return. It must
370 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100371
372 .. tabularcolumns:: |l|L|
373
374 +-----------------------------+----------------------------------------+
375 | Constant | Description |
376 +=============================+========================================+
377 | :const:`FIRST_COMPLETED` | The function will return when any |
378 | | future finishes or is cancelled. |
379 +-----------------------------+----------------------------------------+
380 | :const:`FIRST_EXCEPTION` | The function will return when any |
381 | | future finishes by raising an |
382 | | exception. If no future raises an |
383 | | exception then it is equivalent to |
384 | | :const:`ALL_COMPLETED`. |
385 +-----------------------------+----------------------------------------+
386 | :const:`ALL_COMPLETED` | The function will return when all |
387 | | futures finish or are cancelled. |
388 +-----------------------------+----------------------------------------+
389
Yury Selivanov3faaa882018-09-14 13:32:07 -0700390 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
391 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
393 Usage::
394
Andrew Svetlov88743422017-12-11 17:35:49 +0200395 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396
Victor Stinnerea3183f2013-12-03 01:08:00 +0100397
Yury Selivanov3faaa882018-09-14 13:32:07 -0700398.. function:: as_completed(fs, \*, loop=None, timeout=None)
399
400 Return an iterator which values, when waited for, are
401 :class:`Future` instances.
402
403 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
404 all Futures are done.
405
406 Example::
407
408 for f in as_completed(fs):
409 result = await f
410 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411
Victor Stinner3e09e322013-12-03 01:22:06 +0100412
Yury Selivanov3faaa882018-09-14 13:32:07 -0700413Scheduling From Other Threads
414=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100415
Yury Selivanov3faaa882018-09-14 13:32:07 -0700416.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100417
Yury Selivanov3faaa882018-09-14 13:32:07 -0700418 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100419
Yury Selivanov3faaa882018-09-14 13:32:07 -0700420 Return a :class:`concurrent.futures.Future` to access the result.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100421
Yury Selivanov3faaa882018-09-14 13:32:07 -0700422 This function is meant to be called from a different OS thread
423 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200424
Yury Selivanov3faaa882018-09-14 13:32:07 -0700425 # Create a coroutine
426 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500427
Yury Selivanov3faaa882018-09-14 13:32:07 -0700428 # Submit the coroutine to a given loop
429 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100430
Yury Selivanov3faaa882018-09-14 13:32:07 -0700431 # Wait for the result with an optional timeout argument
432 assert future.result(timeout) == 3
433
434 If an exception is raised in the coroutine, the returned Future
435 will be notified. It can also be used to cancel the task in
436 the event loop::
437
438 try:
439 result = future.result(timeout)
440 except asyncio.TimeoutError:
441 print('The coroutine took too long, cancelling the task...')
442 future.cancel()
443 except Exception as exc:
444 print('The coroutine raised an exception: {!r}'.format(exc))
445 else:
446 print('The coroutine returned: {!r}'.format(result))
447
448 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
449 section of the documentation.
450
451 Unlike other asyncio functions this functions requires the *loop*
452 argument to be passed explicitly.
453
454 .. versionadded:: 3.5.1
455
456
457Introspection
458=============
459
460
461.. function:: current_task(loop=None)
462
463 Return the currently running :class:`Task` instance, or ``None`` if
464 no task is running.
465
466 If *loop* is ``None`` :func:`get_running_loop` is used to get
467 the current loop.
468
469 .. versionadded:: 3.7
470
471
472.. function:: all_tasks(loop=None)
473
474 Return a set of not yet finished :class:`Task` objects run by
475 the loop.
476
477 If *loop* is ``None``, :func:`get_running_loop` is used for getting
478 current loop.
479
480 .. versionadded:: 3.7
481
482
483Task Object
484===========
485
486.. class:: Task(coro, \*, loop=None, name=None)
487
488 A :class:`Future`-like object that wraps a Python
489 :ref:`coroutine <coroutine>`. Not thread-safe.
490
491 Tasks are used to run coroutines in event loops.
492 If a coroutine awaits on a Future, the Task suspends
493 the execution of the coroutine and waits for the completion
494 of the Future. When the Future is *done*, the execution of
495 the wrapped coroutine resumes.
496
497 Event loops use cooperative scheduling: an event loop runs
498 one Task at a time. While a Task awaits for the completion of a
499 Future, the event loop runs other Tasks, callbacks, or performs
500 IO operations.
501
502 Use the high-level :func:`asyncio.create_task` function to create
503 Tasks, or low-level :meth:`loop.create_task` or
504 :func:`ensure_future` functions. Manually instantiating Task
505 objects is discouraged.
506
507 To cancel a running Task use the :meth:`cancel` method. Calling it
508 will cause the Task to throw a :exc:`CancelledError` exception into
509 the wrapped coroutine. If a coroutine is awaiting on a Future
510 object during cancellation, the Future object will be cancelled.
511
512 :meth:`cancelled` can be used to check if the Task was cancelled.
513 The method returns ``True`` if the wrapped coroutine did not
514 suppress the :exc:`CancelledError` exception and was actually
515 cancelled.
516
517 :class:`asyncio.Task` inherits from :class:`Future` all of its
518 APIs except :meth:`Future.set_result` and
519 :meth:`Future.set_exception`.
520
521 Tasks support the :mod:`contextvars` module. When a Task
522 is created it copies the current context and later runs its
523 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400524
525 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700526 Added support for the :mod:`contextvars` module.
527
528 .. versionchanged:: 3.8
529 Added the ``name`` parameter.
530
531 .. method:: cancel()
532
533 Request the Task to be cancelled.
534
535 This arranges for a :exc:`CancelledError` exception to be thrown
536 into the wrapped coroutine on the next cycle of the event loop.
537
538 The coroutine then has a chance to clean up or even deny the
539 request by suppressing the exception with a :keyword:`try` ...
540 ... ``except CancelledError`` ... :keyword:`finally` block.
541 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
542 not guarantee that the Task will be cancelled, although
543 suppressing cancellation completely is not common and is actively
544 discouraged.
545
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700546 .. _asyncio_example_task_cancel:
547
Yury Selivanov3faaa882018-09-14 13:32:07 -0700548 The following example illustrates how coroutines can intercept
549 the cancellation request::
550
551 async def cancel_me():
552 print('cancel_me(): before sleep')
553
554 try:
555 # Wait for 1 hour
556 await asyncio.sleep(3600)
557 except asyncio.CancelledError:
558 print('cancel_me(): cancel sleep')
559 raise
560 finally:
561 print('cancel_me(): after sleep')
562
563 async def main():
564 # Create a "cancel_me" Task
565 task = asyncio.create_task(cancel_me())
566
567 # Wait for 1 second
568 await asyncio.sleep(1)
569
570 task.cancel()
571 try:
572 await task
573 except asyncio.CancelledError:
574 print("main(): cancel_me is cancelled now")
575
576 asyncio.run(main())
577
578 # Expected output:
579 #
580 # cancel_me(): before sleep
581 # cancel_me(): cancel sleep
582 # cancel_me(): after sleep
583 # main(): cancel_me is cancelled now
584
585 .. method:: cancelled()
586
587 Return ``True`` if the Task is *cancelled*.
588
589 The Task is *cancelled* when the cancellation was requested with
590 :meth:`cancel` and the wrapped coroutine propagated the
591 :exc:`CancelledError` exception thrown into it.
592
593 .. method:: done()
594
595 Return ``True`` if the Task is *done*.
596
597 A Task is *done* when the wrapped coroutine either returned
598 a value, raised an exception, or the Task was cancelled.
599
600 .. method:: get_stack(\*, limit=None)
601
602 Return the list of stack frames for this Task.
603
604 If the wrapped coroutine is not done, this returns the stack
605 where it is suspended. If the coroutine has completed
606 successfully or was cancelled, this returns an empty list.
607 If the coroutine was terminated by an exception, this returns
608 the list of traceback frames.
609
610 The frames are always ordered from oldest to newest.
611
612 Only one stack frame is returned for a suspended coroutine.
613
614 The optional *limit* argument sets the maximum number of frames
615 to return; by default all available frames are returned.
616 The ordering of the returned list differs depending on whether
617 a stack or a traceback is returned: the newest frames of a
618 stack are returned, but the oldest frames of a traceback are
619 returned. (This matches the behavior of the traceback module.)
620
621 .. method:: print_stack(\*, limit=None, file=None)
622
623 Print the stack or traceback for this Task.
624
625 This produces output similar to that of the traceback module
626 for the frames retrieved by :meth:`get_stack`.
627
628 The *limit* argument is passed to :meth:`get_stack` directly.
629
630 The *file* argument is an I/O stream to which the output
631 is written; by default output is written to :data:`sys.stderr`.
632
633 .. method:: get_name()
634
635 Return the name of the Task.
636
637 If no name has been explicitly assigned to the Task, the default
638 asyncio Task implementation generates a default name during
639 instantiation.
640
641 .. versionadded:: 3.8
642
643 .. method:: set_name(value)
644
645 Set the name of the Task.
646
647 The *value* argument can be any object, which is then
648 converted to a string.
649
650 In the default Task implementation, the name will be visible
651 in the :func:`repr` output of a task object.
652
653 .. versionadded:: 3.8
654
655 .. classmethod:: all_tasks(loop=None)
656
657 Return a set of all tasks for an event loop.
658
659 By default all tasks for the current event loop are returned.
660 If *loop* is ``None``, the :func:`get_event_loop` function
661 is used to get the current loop.
662
663 This function is **deprecated** and scheduled for removal in
664 Python 3.9. Use the :func:`all_tasks` function instead.
665
666 .. classmethod:: current_task(loop=None)
667
668 Return the currently running task or ``None``.
669
670 If *loop* is ``None``, the :func:`get_event_loop` function
671 is used to get the current loop.
672
673 This function is **deprecated** and scheduled for removal in
674 Python 3.9. Use the :func:`current_task` function instead.
675
676
677.. _asyncio_generator_based_coro:
678
679Generator-based Coroutines
680==========================
681
682.. note::
683
684 Support for generator-based coroutines is **deprecated** and
685 scheduled for removal in Python 4.0.
686
687Generator-based coroutines predate async/await syntax. They are
688Python generators that use ``yield from`` expression is to await
689on Futures and other coroutines.
690
691Generator-based coroutines should be decorated with
692:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
693enforced.
694
695
696.. decorator:: coroutine
697
698 Decorator to mark generator-based coroutines.
699
700 This decorator enables legacy generator-based coroutines to be
701 compatible with async/await code::
702
703 @asyncio.coroutine
704 def old_style_coroutine():
705 yield from asyncio.sleep(1)
706
707 async def main():
708 await old_style_coroutine()
709
710 This decorator is **deprecated** and is scheduled for removal in
711 Python 4.0.
712
713 This decorator should not be used for :keyword:`async def`
714 coroutines.
715
716.. function:: iscoroutine(obj)
717
718 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
719
720 This method is different from :func:`inspect.iscoroutine` because
721 it returns ``True`` for generator-based coroutines decorated with
722 :func:`@coroutine <coroutine>`.
723
724.. function:: iscoroutinefunction(func)
725
726 Return ``True`` if *func* is a :ref:`coroutine function
727 <coroutine>`.
728
729 This method is different from :func:`inspect.iscoroutinefunction`
730 because it returns ``True`` for generator-based coroutine functions
731 decorated with :func:`@coroutine <coroutine>`.