1.. currentmodule:: asyncio
2
3
4====================
5Coroutines and Tasks
6====================
7
8This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
10
11.. contents::
12   :depth: 1
13   :local:
14
15
16.. _coroutine:
17
18Coroutines
19==========
20
21:term:`Coroutines <coroutine>` declared with the async/await syntax is the
22preferred way of writing asyncio applications.  For example, the following
23snippet of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
25
26    >>> import asyncio
27
28    >>> async def main():
29    ...     print('hello')
30    ...     await asyncio.sleep(1)
31    ...     print('world')
32
33    >>> asyncio.run(main())
34    hello
35    world
36
37Note that simply calling a coroutine will not schedule it to
38be executed::
39
40    >>> main()
41    <coroutine object main at 0x1053bb7c8>
42
43To actually run a coroutine, asyncio provides three main mechanisms:
44
45* The :func:`asyncio.run` function to run the top-level
46  entry point "main()" function (see the above example.)
47
48* 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::
51
52      import asyncio
53      import time
54
55      async def say_after(delay, what):
56          await asyncio.sleep(delay)
57          print(what)
58
59      async def main():
60          print(f"started at {time.strftime('%X')}")
61
62          await say_after(1, 'hello')
63          await say_after(2, 'world')
64
65          print(f"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
79  Let's modify the above example and run two ``say_after`` coroutines
80  *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(f"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(f"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
106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
112We say that an object is an **awaitable** object if it can be used
113in an :keyword:`await` expression.  Many asyncio APIs are designed to
114accept awaitables.
115
116There are three main types of *awaitable* objects:
117**coroutines**, **Tasks**, and **Futures**.
118
119
120.. rubric:: Coroutines
121
122Python coroutines are *awaitables* and therefore can be awaited from
123other coroutines::
124
125    import asyncio
126
127    async def nested():
128        return 42
129
130    async def main():
131        # Nothing happens if we just call "nested()".
132        # A coroutine object is created but not awaited,
133        # so it *won't run at all*.
134        nested()
135
136        # Let's do it differently now and await it:
137        print(await nested())  # will print "42".
138
139    asyncio.run(main())
140
141.. important::
142
143   In this documentation the term "coroutine" can be used for
144   two closely related concepts:
145
146   * a *coroutine function*: an :keyword:`async def` function;
147
148   * a *coroutine object*: an object returned by calling a
149     *coroutine function*.
150
151asyncio also supports legacy :ref:`generator-based
152<asyncio_generator_based_coro>` coroutines.
153
154
155.. rubric:: Tasks
156
157*Tasks* are used to schedule coroutines *concurrently*.
158
159When a coroutine is wrapped into a *Task* with functions like
160:func:`asyncio.create_task` the coroutine is automatically
161scheduled to run soon::
162
163    import asyncio
164
165    async def nested():
166        return 42
167
168    async def main():
169        # Schedule nested() to run soon concurrently
170        # with "main()".
171        task = asyncio.create_task(nested())
172
173        # "task" can now be used to cancel "nested()", or
174        # can simply be awaited to wait until it is complete:
175        await task
176
177    asyncio.run(main())
178
179
180.. rubric:: Futures
181
182A :class:`Future` is a special **low-level** awaitable object that
183represents an **eventual result** of an asynchronous operation.
184
185When a Future object is *awaited* it means that the coroutine will
186wait until the Future is resolved in some other place.
187
188Future objects in asyncio are needed to allow callback-based code
189to be used with async/await.
190
191Normally **there is no need** to create Future objects at the
192application level code.
193
194Future objects, sometimes exposed by libraries and some asyncio
195APIs, can be awaited::
196
197    async def main():
198        await function_that_returns_a_future_object()
199
200        # this is also valid:
201        await asyncio.gather(
202            function_that_returns_a_future_object(),
203            some_python_coroutine()
204        )
205
206A good example of a low-level function that returns a Future object
207is :meth:`loop.run_in_executor`.
208
209
210Running an asyncio Program
211==========================
212
213.. function:: run(coro, *, debug=False)
214
215    Execute the :term:`coroutine` *coro* and return the result.
216
217    This function runs the passed coroutine, taking care of
218    managing the asyncio event loop, *finalizing asynchronous
219    generators*, and closing the threadpool.
220
221    This function cannot be called when another asyncio event loop is
222    running in the same thread.
223
224    If *debug* is ``True``, the event loop will be run in debug mode.
225
226    This function always creates a new event loop and closes it at
227    the end.  It should be used as a main entry point for asyncio
228    programs, and should ideally only be called once.
229
230    Example::
231
232        async def main():
233            await asyncio.sleep(1)
234            print('hello')
235
236        asyncio.run(main())
237
238    .. versionadded:: 3.7
239
240    .. versionchanged:: 3.9
241       Updated to use :meth:`loop.shutdown_default_executor`.
242
243    .. note::
244       The source code for ``asyncio.run()`` can be found in
245       :source:`Lib/asyncio/runners.py`.
246
247Creating Tasks
248==============
249
250.. function:: create_task(coro, *, name=None)
251
252   Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
253   and schedule its execution.  Return the Task object.
254
255   If *name* is not ``None``, it is set as the name of the task using
256   :meth:`Task.set_name`.
257
258   The task is executed in the loop returned by :func:`get_running_loop`,
259   :exc:`RuntimeError` is raised if there is no running loop in
260   current thread.
261
262   This function has been **added in Python 3.7**.  Prior to
263   Python 3.7, the low-level :func:`asyncio.ensure_future` function
264   can be used instead::
265
266       async def coro():
267           ...
268
269       # In Python 3.7+
270       task = asyncio.create_task(coro())
271       ...
272
273       # This works in all Python versions but is less readable
274       task = asyncio.ensure_future(coro())
275       ...
276
277   .. important::
278
279      Save a reference to the result of this function, to avoid
280      a task disappearing mid execution.
281
282   .. versionadded:: 3.7
283
284   .. versionchanged:: 3.8
285      Added the ``name`` parameter.
286
287
288Sleeping
289========
290
291.. coroutinefunction:: sleep(delay, result=None)
292
293   Block for *delay* seconds.
294
295   If *result* is provided, it is returned to the caller
296   when the coroutine completes.
297
298   ``sleep()`` always suspends the current task, allowing other tasks
299   to run.
300
301   Setting the delay to 0 provides an optimized path to allow other
302   tasks to run. This can be used by long-running functions to avoid
303   blocking the event loop for the full duration of the function call.
304
305   .. deprecated-removed:: 3.8 3.10
306      The ``loop`` parameter.  This function has been implicitly getting the
307      current running loop since 3.7.  See
308      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
309      for more information.
310
311   .. _asyncio_example_sleep:
312
313   Example of coroutine displaying the current date every second
314   for 5 seconds::
315
316    import asyncio
317    import datetime
318
319    async def display_date():
320        loop = asyncio.get_running_loop()
321        end_time = loop.time() + 5.0
322        while True:
323            print(datetime.datetime.now())
324            if (loop.time() + 1.0) >= end_time:
325                break
326            await asyncio.sleep(1)
327
328    asyncio.run(display_date())
329
330
331   .. deprecated-removed:: 3.8 3.10
332
333      The ``loop`` parameter.  This function has been implicitly getting the
334      current running loop since 3.7.  See
335      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
336      for more information.
337
338
339Running Tasks Concurrently
340==========================
341
342.. awaitablefunction:: gather(*aws, return_exceptions=False)
343
344   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
345   sequence *concurrently*.
346
347   If any awaitable in *aws* is a coroutine, it is automatically
348   scheduled as a Task.
349
350   If all awaitables are completed successfully, the result is an
351   aggregate list of returned values.  The order of result values
352   corresponds to the order of awaitables in *aws*.
353
354   If *return_exceptions* is ``False`` (default), the first
355   raised exception is immediately propagated to the task that
356   awaits on ``gather()``.  Other awaitables in the *aws* sequence
357   **won't be cancelled** and will continue to run.
358
359   If *return_exceptions* is ``True``, exceptions are treated the
360   same as successful results, and aggregated in the result list.
361
362   If ``gather()`` is *cancelled*, all submitted awaitables
363   (that have not completed yet) are also *cancelled*.
364
365   If any Task or Future from the *aws* sequence is *cancelled*, it is
366   treated as if it raised :exc:`CancelledError` -- the ``gather()``
367   call is **not** cancelled in this case.  This is to prevent the
368   cancellation of one submitted Task/Future to cause other
369   Tasks/Futures to be cancelled.
370
371   .. deprecated-removed:: 3.8 3.10
372      The ``loop`` parameter.  This function has been implicitly getting the
373      current running loop since 3.7.  See
374      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
375      for more information.
376
377   .. _asyncio_example_gather:
378
379   Example::
380
381      import asyncio
382
383      async def factorial(name, number):
384          f = 1
385          for i in range(2, number + 1):
386              print(f"Task {name}: Compute factorial({number}), currently i={i}...")
387              await asyncio.sleep(1)
388              f *= i
389          print(f"Task {name}: factorial({number}) = {f}")
390          return f
391
392      async def main():
393          # Schedule three calls *concurrently*:
394          L = await asyncio.gather(
395              factorial("A", 2),
396              factorial("B", 3),
397              factorial("C", 4),
398          )
399          print(L)
400
401      asyncio.run(main())
402
403      # Expected output:
404      #
405      #     Task A: Compute factorial(2), currently i=2...
406      #     Task B: Compute factorial(3), currently i=2...
407      #     Task C: Compute factorial(4), currently i=2...
408      #     Task A: factorial(2) = 2
409      #     Task B: Compute factorial(3), currently i=3...
410      #     Task C: Compute factorial(4), currently i=3...
411      #     Task B: factorial(3) = 6
412      #     Task C: Compute factorial(4), currently i=4...
413      #     Task C: factorial(4) = 24
414      #     [2, 6, 24]
415
416   .. note::
417      If *return_exceptions* is False, cancelling gather() after it
418      has been marked done won't cancel any submitted awaitables.
419      For instance, gather can be marked done after propagating an
420      exception to the caller, therefore, calling ``gather.cancel()``
421      after catching an exception (raised by one of the awaitables) from
422      gather won't cancel any other awaitables.
423
424   .. versionchanged:: 3.7
425      If the *gather* itself is cancelled, the cancellation is
426      propagated regardless of *return_exceptions*.
427
428   .. deprecated-removed:: 3.8 3.10
429      The ``loop`` parameter.  This function has been implicitly getting the
430      current running loop since 3.7.  See
431      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
432      for more information.
433
434   .. deprecated:: 3.10
435      Deprecation warning is emitted if no positional arguments are provided
436      or not all positional arguments are Future-like objects
437      and there is no running event loop.
438
439
440Shielding From Cancellation
441===========================
442
443.. awaitablefunction:: shield(aw)
444
445   Protect an :ref:`awaitable object <asyncio-awaitables>`
446   from being :meth:`cancelled <Task.cancel>`.
447
448   If *aw* is a coroutine it is automatically scheduled as a Task.
449
450   The statement::
451
452       res = await shield(something())
453
454   is equivalent to::
455
456       res = await something()
457
458   *except* that if the coroutine containing it is cancelled, the
459   Task running in ``something()`` is not cancelled.  From the point
460   of view of ``something()``, the cancellation did not happen.
461   Although its caller is still cancelled, so the "await" expression
462   still raises a :exc:`CancelledError`.
463
464   If ``something()`` is cancelled by other means (i.e. from within
465   itself) that would also cancel ``shield()``.
466
467   If it is desired to completely ignore cancellation (not recommended)
468   the ``shield()`` function should be combined with a try/except
469   clause, as follows::
470
471       try:
472           res = await shield(something())
473       except CancelledError:
474           res = None
475
476   .. deprecated-removed:: 3.8 3.10
477      The ``loop`` parameter.  This function has been implicitly getting the
478      current running loop since 3.7.  See
479      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
480      for more information.
481
482   .. deprecated:: 3.10
483      Deprecation warning is emitted if *aw* is not Future-like object
484      and there is no running event loop.
485
486
487Timeouts
488========
489
490.. coroutinefunction:: wait_for(aw, timeout)
491
492   Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
493   to complete with a timeout.
494
495   If *aw* is a coroutine it is automatically scheduled as a Task.
496
497   *timeout* can either be ``None`` or a float or int number of seconds
498   to wait for.  If *timeout* is ``None``, block until the future
499   completes.
500
501   If a timeout occurs, it cancels the task and raises
502   :exc:`asyncio.TimeoutError`.
503
504   To avoid the task :meth:`cancellation <Task.cancel>`,
505   wrap it in :func:`shield`.
506
507   The function will wait until the future is actually cancelled,
508   so the total wait time may exceed the *timeout*. If an exception
509   happens during cancellation, it is propagated.
510
511   If the wait is cancelled, the future *aw* is also cancelled.
512
513   .. deprecated-removed:: 3.8 3.10
514      The ``loop`` parameter.  This function has been implicitly getting the
515      current running loop since 3.7.  See
516      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
517      for more information.
518
519   .. _asyncio_example_waitfor:
520
521   Example::
522
523       async def eternity():
524           # Sleep for one hour
525           await asyncio.sleep(3600)
526           print('yay!')
527
528       async def main():
529           # Wait for at most 1 second
530           try:
531               await asyncio.wait_for(eternity(), timeout=1.0)
532           except asyncio.TimeoutError:
533               print('timeout!')
534
535       asyncio.run(main())
536
537       # Expected output:
538       #
539       #     timeout!
540
541   .. versionchanged:: 3.7
542      When *aw* is cancelled due to a timeout, ``wait_for`` waits
543      for *aw* to be cancelled.  Previously, it raised
544      :exc:`asyncio.TimeoutError` immediately.
545
546   .. deprecated-removed:: 3.8 3.10
547      The ``loop`` parameter.  This function has been implicitly getting the
548      current running loop since 3.7.  See
549      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
550      for more information.
551
552
553Waiting Primitives
554==================
555
556.. coroutinefunction:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
557
558   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
559   iterable concurrently and block until the condition specified
560   by *return_when*.
561
562   The *aws* iterable must not be empty.
563
564   Returns two sets of Tasks/Futures: ``(done, pending)``.
565
566   Usage::
567
568        done, pending = await asyncio.wait(aws)
569
570   *timeout* (a float or int), if specified, can be used to control
571   the maximum number of seconds to wait before returning.
572
573   Note that this function does not raise :exc:`asyncio.TimeoutError`.
574   Futures or Tasks that aren't done when the timeout occurs are simply
575   returned in the second set.
576
577   *return_when* indicates when this function should return.  It must
578   be one of the following constants:
579
580   .. tabularcolumns:: |l|L|
581
582   +-----------------------------+----------------------------------------+
583   | Constant                    | Description                            |
584   +=============================+========================================+
585   | :const:`FIRST_COMPLETED`    | The function will return when any      |
586   |                             | future finishes or is cancelled.       |
587   +-----------------------------+----------------------------------------+
588   | :const:`FIRST_EXCEPTION`    | The function will return when any      |
589   |                             | future finishes by raising an          |
590   |                             | exception.  If no future raises an     |
591   |                             | exception then it is equivalent to     |
592   |                             | :const:`ALL_COMPLETED`.                |
593   +-----------------------------+----------------------------------------+
594   | :const:`ALL_COMPLETED`      | The function will return when all      |
595   |                             | futures finish or are cancelled.       |
596   +-----------------------------+----------------------------------------+
597
598   Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
599   futures when a timeout occurs.
600
601   .. deprecated:: 3.8
602
603      If any awaitable in *aws* is a coroutine, it is automatically
604      scheduled as a Task.  Passing coroutines objects to
605      ``wait()`` directly is deprecated as it leads to
606      :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
607
608   .. deprecated-removed:: 3.8 3.10
609      The ``loop`` parameter.  This function has been implicitly getting the
610      current running loop since 3.7.  See
611      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
612      for more information.
613
614   .. _asyncio_example_wait_coroutine:
615   .. note::
616
617      ``wait()`` schedules coroutines as Tasks automatically and later
618      returns those implicitly created Task objects in ``(done, pending)``
619      sets.  Therefore the following code won't work as expected::
620
621          async def foo():
622              return 42
623
624          coro = foo()
625          done, pending = await asyncio.wait({coro})
626
627          if coro in done:
628              # This branch will never be run!
629
630      Here is how the above snippet can be fixed::
631
632          async def foo():
633              return 42
634
635          task = asyncio.create_task(foo())
636          done, pending = await asyncio.wait({task})
637
638          if task in done:
639              # Everything will work as expected now.
640
641   .. deprecated-removed:: 3.8 3.10
642
643      The ``loop`` parameter.  This function has been implicitly getting the
644      current running loop since 3.7.  See
645      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
646      for more information.
647
648   .. deprecated-removed:: 3.8 3.11
649
650      Passing coroutine objects to ``wait()`` directly is
651      deprecated.
652
653
654.. function:: as_completed(aws, *, timeout=None)
655
656   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
657   iterable concurrently.  Return an iterator of coroutines.
658   Each coroutine returned can be awaited to get the earliest next
659   result from the iterable of the remaining awaitables.
660
661   Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
662   all Futures are done.
663
664   .. deprecated-removed:: 3.8 3.10
665      The ``loop`` parameter.  This function has been implicitly getting the
666      current running loop since 3.7.  See
667      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
668      for more information.
669
670   Example::
671
672       for coro in as_completed(aws):
673           earliest_result = await coro
674           # ...
675
676   .. deprecated-removed:: 3.8 3.10
677      The ``loop`` parameter.  This function has been implicitly getting the
678      current running loop since 3.7.  See
679      :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
680      for more information.
681
682   .. deprecated:: 3.10
683      Deprecation warning is emitted if not all awaitable objects in the *aws*
684      iterable are Future-like objects and there is no running event loop.
685
686
687Running in Threads
688==================
689
690.. coroutinefunction:: to_thread(func, /, *args, **kwargs)
691
692   Asynchronously run function *func* in a separate thread.
693
694   Any \*args and \*\*kwargs supplied for this function are directly passed
695   to *func*. Also, the current :class:`contextvars.Context` is propagated,
696   allowing context variables from the event loop thread to be accessed in the
697   separate thread.
698
699   Return a coroutine that can be awaited to get the eventual result of *func*.
700
701   This coroutine function is primarily intended to be used for executing
702   IO-bound functions/methods that would otherwise block the event loop if
703   they were ran in the main thread. For example::
704
705       def blocking_io():
706           print(f"start blocking_io at {time.strftime('%X')}")
707           # Note that time.sleep() can be replaced with any blocking
708           # IO-bound operation, such as file operations.
709           time.sleep(1)
710           print(f"blocking_io complete at {time.strftime('%X')}")
711
712       async def main():
713           print(f"started main at {time.strftime('%X')}")
714
715           await asyncio.gather(
716               asyncio.to_thread(blocking_io),
717               asyncio.sleep(1))
718
719           print(f"finished main at {time.strftime('%X')}")
720
721
722       asyncio.run(main())
723
724       # Expected output:
725       #
726       # started main at 19:50:53
727       # start blocking_io at 19:50:53
728       # blocking_io complete at 19:50:54
729       # finished main at 19:50:54
730
731   Directly calling `blocking_io()` in any coroutine would block the event loop
732   for its duration, resulting in an additional 1 second of run time. Instead,
733   by using `asyncio.to_thread()`, we can run it in a separate thread without
734   blocking the event loop.
735
736   .. note::
737
738      Due to the :term:`GIL`, `asyncio.to_thread()` can typically only be used
739      to make IO-bound functions non-blocking. However, for extension modules
740      that release the GIL or alternative Python implementations that don't
741      have one, `asyncio.to_thread()` can also be used for CPU-bound functions.
742
743   .. versionadded:: 3.9
744
745
746Scheduling From Other Threads
747=============================
748
749.. function:: run_coroutine_threadsafe(coro, loop)
750
751   Submit a coroutine to the given event loop.  Thread-safe.
752
753   Return a :class:`concurrent.futures.Future` to wait for the result
754   from another OS thread.
755
756   This function is meant to be called from a different OS thread
757   than the one where the event loop is running.  Example::
758
759     # Create a coroutine
760     coro = asyncio.sleep(1, result=3)
761
762     # Submit the coroutine to a given loop
763     future = asyncio.run_coroutine_threadsafe(coro, loop)
764
765     # Wait for the result with an optional timeout argument
766     assert future.result(timeout) == 3
767
768   If an exception is raised in the coroutine, the returned Future
769   will be notified.  It can also be used to cancel the task in
770   the event loop::
771
772     try:
773         result = future.result(timeout)
774     except concurrent.futures.TimeoutError:
775         print('The coroutine took too long, cancelling the task...')
776         future.cancel()
777     except Exception as exc:
778         print(f'The coroutine raised an exception: {exc!r}')
779     else:
780         print(f'The coroutine returned: {result!r}')
781
782   See the :ref:`concurrency and multithreading <asyncio-multithreading>`
783   section of the documentation.
784
785   Unlike other asyncio functions this function requires the *loop*
786   argument to be passed explicitly.
787
788   .. versionadded:: 3.5.1
789
790
791Introspection
792=============
793
794
795.. function:: current_task(loop=None)
796
797   Return the currently running :class:`Task` instance, or ``None`` if
798   no task is running.
799
800   If *loop* is ``None`` :func:`get_running_loop` is used to get
801   the current loop.
802
803   .. versionadded:: 3.7
804
805
806.. function:: all_tasks(loop=None)
807
808   Return a set of not yet finished :class:`Task` objects run by
809   the loop.
810
811   If *loop* is ``None``, :func:`get_running_loop` is used for getting
812   current loop.
813
814   .. versionadded:: 3.7
815
816
817Task Object
818===========
819
820.. class:: Task(coro, *, loop=None, name=None)
821
822   A :class:`Future-like <Future>` object that runs a Python
823   :ref:`coroutine <coroutine>`.  Not thread-safe.
824
825   Tasks are used to run coroutines in event loops.
826   If a coroutine awaits on a Future, the Task suspends
827   the execution of the coroutine and waits for the completion
828   of the Future.  When the Future is *done*, the execution of
829   the wrapped coroutine resumes.
830
831   Event loops use cooperative scheduling: an event loop runs
832   one Task at a time.  While a Task awaits for the completion of a
833   Future, the event loop runs other Tasks, callbacks, or performs
834   IO operations.
835
836   Use the high-level :func:`asyncio.create_task` function to create
837   Tasks, or the low-level :meth:`loop.create_task` or
838   :func:`ensure_future` functions.  Manual instantiation of Tasks
839   is discouraged.
840
841   To cancel a running Task use the :meth:`cancel` method.  Calling it
842   will cause the Task to throw a :exc:`CancelledError` exception into
843   the wrapped coroutine.  If a coroutine is awaiting on a Future
844   object during cancellation, the Future object will be cancelled.
845
846   :meth:`cancelled` can be used to check if the Task was cancelled.
847   The method returns ``True`` if the wrapped coroutine did not
848   suppress the :exc:`CancelledError` exception and was actually
849   cancelled.
850
851   :class:`asyncio.Task` inherits from :class:`Future` all of its
852   APIs except :meth:`Future.set_result` and
853   :meth:`Future.set_exception`.
854
855   Tasks support the :mod:`contextvars` module.  When a Task
856   is created it copies the current context and later runs its
857   coroutine in the copied context.
858
859   .. versionchanged:: 3.7
860      Added support for the :mod:`contextvars` module.
861
862   .. versionchanged:: 3.8
863      Added the ``name`` parameter.
864
865   .. deprecated-removed:: 3.8 3.10
866      The *loop* parameter.
867
868   .. deprecated:: 3.10
869      Deprecation warning is emitted if *loop* is not specified
870      and there is no running event loop.
871
872   .. method:: cancel(msg=None)
873
874      Request the Task to be cancelled.
875
876      This arranges for a :exc:`CancelledError` exception to be thrown
877      into the wrapped coroutine on the next cycle of the event loop.
878
879      The coroutine then has a chance to clean up or even deny the
880      request by suppressing the exception with a :keyword:`try` ...
881      ... ``except CancelledError`` ... :keyword:`finally` block.
882      Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
883      not guarantee that the Task will be cancelled, although
884      suppressing cancellation completely is not common and is actively
885      discouraged.
886
887      .. versionchanged:: 3.9
888         Added the ``msg`` parameter.
889
890      .. _asyncio_example_task_cancel:
891
892      The following example illustrates how coroutines can intercept
893      the cancellation request::
894
895          async def cancel_me():
896              print('cancel_me(): before sleep')
897
898              try:
899                  # Wait for 1 hour
900                  await asyncio.sleep(3600)
901              except asyncio.CancelledError:
902                  print('cancel_me(): cancel sleep')
903                  raise
904              finally:
905                  print('cancel_me(): after sleep')
906
907          async def main():
908              # Create a "cancel_me" Task
909              task = asyncio.create_task(cancel_me())
910
911              # Wait for 1 second
912              await asyncio.sleep(1)
913
914              task.cancel()
915              try:
916                  await task
917              except asyncio.CancelledError:
918                  print("main(): cancel_me is cancelled now")
919
920          asyncio.run(main())
921
922          # Expected output:
923          #
924          #     cancel_me(): before sleep
925          #     cancel_me(): cancel sleep
926          #     cancel_me(): after sleep
927          #     main(): cancel_me is cancelled now
928
929   .. method:: cancelled()
930
931      Return ``True`` if the Task is *cancelled*.
932
933      The Task is *cancelled* when the cancellation was requested with
934      :meth:`cancel` and the wrapped coroutine propagated the
935      :exc:`CancelledError` exception thrown into it.
936
937   .. method:: done()
938
939      Return ``True`` if the Task is *done*.
940
941      A Task is *done* when the wrapped coroutine either returned
942      a value, raised an exception, or the Task was cancelled.
943
944   .. method:: result()
945
946      Return the result of the Task.
947
948      If the Task is *done*, the result of the wrapped coroutine
949      is returned (or if the coroutine raised an exception, that
950      exception is re-raised.)
951
952      If the Task has been *cancelled*, this method raises
953      a :exc:`CancelledError` exception.
954
955      If the Task's result isn't yet available, this method raises
956      a :exc:`InvalidStateError` exception.
957
958   .. method:: exception()
959
960      Return the exception of the Task.
961
962      If the wrapped coroutine raised an exception that exception
963      is returned.  If the wrapped coroutine returned normally
964      this method returns ``None``.
965
966      If the Task has been *cancelled*, this method raises a
967      :exc:`CancelledError` exception.
968
969      If the Task isn't *done* yet, this method raises an
970      :exc:`InvalidStateError` exception.
971
972   .. method:: add_done_callback(callback, *, context=None)
973
974      Add a callback to be run when the Task is *done*.
975
976      This method should only be used in low-level callback-based code.
977
978      See the documentation of :meth:`Future.add_done_callback`
979      for more details.
980
981   .. method:: remove_done_callback(callback)
982
983      Remove *callback* from the callbacks list.
984
985      This method should only be used in low-level callback-based code.
986
987      See the documentation of :meth:`Future.remove_done_callback`
988      for more details.
989
990   .. method:: get_stack(*, limit=None)
991
992      Return the list of stack frames for this Task.
993
994      If the wrapped coroutine is not done, this returns the stack
995      where it is suspended.  If the coroutine has completed
996      successfully or was cancelled, this returns an empty list.
997      If the coroutine was terminated by an exception, this returns
998      the list of traceback frames.
999
1000      The frames are always ordered from oldest to newest.
1001
1002      Only one stack frame is returned for a suspended coroutine.
1003
1004      The optional *limit* argument sets the maximum number of frames
1005      to return; by default all available frames are returned.
1006      The ordering of the returned list differs depending on whether
1007      a stack or a traceback is returned: the newest frames of a
1008      stack are returned, but the oldest frames of a traceback are
1009      returned.  (This matches the behavior of the traceback module.)
1010
1011   .. method:: print_stack(*, limit=None, file=None)
1012
1013      Print the stack or traceback for this Task.
1014
1015      This produces output similar to that of the traceback module
1016      for the frames retrieved by :meth:`get_stack`.
1017
1018      The *limit* argument is passed to :meth:`get_stack` directly.
1019
1020      The *file* argument is an I/O stream to which the output
1021      is written; by default output is written to :data:`sys.stderr`.
1022
1023   .. method:: get_coro()
1024
1025      Return the coroutine object wrapped by the :class:`Task`.
1026
1027      .. versionadded:: 3.8
1028
1029   .. method:: get_name()
1030
1031      Return the name of the Task.
1032
1033      If no name has been explicitly assigned to the Task, the default
1034      asyncio Task implementation generates a default name during
1035      instantiation.
1036
1037      .. versionadded:: 3.8
1038
1039   .. method:: set_name(value)
1040
1041      Set the name of the Task.
1042
1043      The *value* argument can be any object, which is then
1044      converted to a string.
1045
1046      In the default Task implementation, the name will be visible
1047      in the :func:`repr` output of a task object.
1048
1049      .. versionadded:: 3.8
1050
1051
1052.. _asyncio_generator_based_coro:
1053
1054Generator-based Coroutines
1055==========================
1056
1057.. note::
1058
1059   Support for generator-based coroutines is **deprecated** and
1060   is scheduled for removal in Python 3.10.
1061
1062Generator-based coroutines predate async/await syntax.  They are
1063Python generators that use ``yield from`` expressions to await
1064on Futures and other coroutines.
1065
1066Generator-based coroutines should be decorated with
1067:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
1068enforced.
1069
1070
1071.. decorator:: coroutine
1072
1073    Decorator to mark generator-based coroutines.
1074
1075    This decorator enables legacy generator-based coroutines to be
1076    compatible with async/await code::
1077
1078        @asyncio.coroutine
1079        def old_style_coroutine():
1080            yield from asyncio.sleep(1)
1081
1082        async def main():
1083            await old_style_coroutine()
1084
1085    This decorator should not be used for :keyword:`async def`
1086    coroutines.
1087
1088    .. deprecated-removed:: 3.8 3.10
1089
1090       Use :keyword:`async def` instead.
1091
1092.. function:: iscoroutine(obj)
1093
1094   Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
1095
1096   This method is different from :func:`inspect.iscoroutine` because
1097   it returns ``True`` for generator-based coroutines.
1098
1099.. function:: iscoroutinefunction(func)
1100
1101   Return ``True`` if *func* is a :ref:`coroutine function
1102   <coroutine>`.
1103
1104   This method is different from :func:`inspect.iscoroutinefunction`
1105   because it returns ``True`` for generator-based coroutine functions
1106   decorated with :func:`@coroutine <coroutine>`.
1107