• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 and *finalizing asynchronous
219    generators*.
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
241    .. note::
242       The source code for ``asyncio.run()`` can be found in
243       :source:`Lib/asyncio/runners.py`.
244
245Creating Tasks
246==============
247
248.. function:: create_task(coro, \*, name=None)
249
250   Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
251   and schedule its execution.  Return the Task object.
252
253   If *name* is not ``None``, it is set as the name of the task using
254   :meth:`Task.set_name`.
255
256   The task is executed in the loop returned by :func:`get_running_loop`,
257   :exc:`RuntimeError` is raised if there is no running loop in
258   current thread.
259
260   This function has been **added in Python 3.7**.  Prior to
261   Python 3.7, the low-level :func:`asyncio.ensure_future` function
262   can be used instead::
263
264       async def coro():
265           ...
266
267       # In Python 3.7+
268       task = asyncio.create_task(coro())
269       ...
270
271       # This works in all Python versions but is less readable
272       task = asyncio.ensure_future(coro())
273       ...
274
275   .. versionadded:: 3.7
276
277   .. versionchanged:: 3.8
278      Added the ``name`` parameter.
279
280
281Sleeping
282========
283
284.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
285
286   Block for *delay* seconds.
287
288   If *result* is provided, it is returned to the caller
289   when the coroutine completes.
290
291   ``sleep()`` always suspends the current task, allowing other tasks
292   to run.
293
294   .. deprecated-removed:: 3.8 3.10
295      The *loop* parameter.
296
297   .. _asyncio_example_sleep:
298
299   Example of coroutine displaying the current date every second
300   for 5 seconds::
301
302    import asyncio
303    import datetime
304
305    async def display_date():
306        loop = asyncio.get_running_loop()
307        end_time = loop.time() + 5.0
308        while True:
309            print(datetime.datetime.now())
310            if (loop.time() + 1.0) >= end_time:
311                break
312            await asyncio.sleep(1)
313
314    asyncio.run(display_date())
315
316
317Running Tasks Concurrently
318==========================
319
320.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
321
322   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
323   sequence *concurrently*.
324
325   If any awaitable in *aws* is a coroutine, it is automatically
326   scheduled as a Task.
327
328   If all awaitables are completed successfully, the result is an
329   aggregate list of returned values.  The order of result values
330   corresponds to the order of awaitables in *aws*.
331
332   If *return_exceptions* is ``False`` (default), the first
333   raised exception is immediately propagated to the task that
334   awaits on ``gather()``.  Other awaitables in the *aws* sequence
335   **won't be cancelled** and will continue to run.
336
337   If *return_exceptions* is ``True``, exceptions are treated the
338   same as successful results, and aggregated in the result list.
339
340   If ``gather()`` is *cancelled*, all submitted awaitables
341   (that have not completed yet) are also *cancelled*.
342
343   If any Task or Future from the *aws* sequence is *cancelled*, it is
344   treated as if it raised :exc:`CancelledError` -- the ``gather()``
345   call is **not** cancelled in this case.  This is to prevent the
346   cancellation of one submitted Task/Future to cause other
347   Tasks/Futures to be cancelled.
348
349   .. deprecated-removed:: 3.8 3.10
350      The *loop* parameter.
351
352   .. _asyncio_example_gather:
353
354   Example::
355
356      import asyncio
357
358      async def factorial(name, number):
359          f = 1
360          for i in range(2, number + 1):
361              print(f"Task {name}: Compute factorial({i})...")
362              await asyncio.sleep(1)
363              f *= i
364          print(f"Task {name}: factorial({number}) = {f}")
365
366      async def main():
367          # Schedule three calls *concurrently*:
368          await asyncio.gather(
369              factorial("A", 2),
370              factorial("B", 3),
371              factorial("C", 4),
372          )
373
374      asyncio.run(main())
375
376      # Expected output:
377      #
378      #     Task A: Compute factorial(2)...
379      #     Task B: Compute factorial(2)...
380      #     Task C: Compute factorial(2)...
381      #     Task A: factorial(2) = 2
382      #     Task B: Compute factorial(3)...
383      #     Task C: Compute factorial(3)...
384      #     Task B: factorial(3) = 6
385      #     Task C: Compute factorial(4)...
386      #     Task C: factorial(4) = 24
387
388   .. note::
389      If *return_exceptions* is False, cancelling gather() after it
390      has been marked done won't cancel any submitted awaitables.
391      For instance, gather can be marked done after propagating an
392      exception to the caller, therefore, calling ``gather.cancel()``
393      after catching an exception (raised by one of the awaitables) from
394      gather won't cancel any other awaitables.
395
396   .. versionchanged:: 3.7
397      If the *gather* itself is cancelled, the cancellation is
398      propagated regardless of *return_exceptions*.
399
400
401Shielding From Cancellation
402===========================
403
404.. awaitablefunction:: shield(aw, \*, loop=None)
405
406   Protect an :ref:`awaitable object <asyncio-awaitables>`
407   from being :meth:`cancelled <Task.cancel>`.
408
409   If *aw* is a coroutine it is automatically scheduled as a Task.
410
411   The statement::
412
413       res = await shield(something())
414
415   is equivalent to::
416
417       res = await something()
418
419   *except* that if the coroutine containing it is cancelled, the
420   Task running in ``something()`` is not cancelled.  From the point
421   of view of ``something()``, the cancellation did not happen.
422   Although its caller is still cancelled, so the "await" expression
423   still raises a :exc:`CancelledError`.
424
425   If ``something()`` is cancelled by other means (i.e. from within
426   itself) that would also cancel ``shield()``.
427
428   If it is desired to completely ignore cancellation (not recommended)
429   the ``shield()`` function should be combined with a try/except
430   clause, as follows::
431
432       try:
433           res = await shield(something())
434       except CancelledError:
435           res = None
436
437   .. deprecated-removed:: 3.8 3.10
438      The *loop* parameter.
439
440
441Timeouts
442========
443
444.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
445
446   Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
447   to complete with a timeout.
448
449   If *aw* is a coroutine it is automatically scheduled as a Task.
450
451   *timeout* can either be ``None`` or a float or int number of seconds
452   to wait for.  If *timeout* is ``None``, block until the future
453   completes.
454
455   If a timeout occurs, it cancels the task and raises
456   :exc:`asyncio.TimeoutError`.
457
458   To avoid the task :meth:`cancellation <Task.cancel>`,
459   wrap it in :func:`shield`.
460
461   The function will wait until the future is actually cancelled,
462   so the total wait time may exceed the *timeout*.
463
464   If the wait is cancelled, the future *aw* is also cancelled.
465
466   .. deprecated-removed:: 3.8 3.10
467      The *loop* parameter.
468
469   .. _asyncio_example_waitfor:
470
471   Example::
472
473       async def eternity():
474           # Sleep for one hour
475           await asyncio.sleep(3600)
476           print('yay!')
477
478       async def main():
479           # Wait for at most 1 second
480           try:
481               await asyncio.wait_for(eternity(), timeout=1.0)
482           except asyncio.TimeoutError:
483               print('timeout!')
484
485       asyncio.run(main())
486
487       # Expected output:
488       #
489       #     timeout!
490
491   .. versionchanged:: 3.7
492      When *aw* is cancelled due to a timeout, ``wait_for`` waits
493      for *aw* to be cancelled.  Previously, it raised
494      :exc:`asyncio.TimeoutError` immediately.
495
496
497Waiting Primitives
498==================
499
500.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
501                            return_when=ALL_COMPLETED)
502
503   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
504   set concurrently and block until the condition specified
505   by *return_when*.
506
507   Returns two sets of Tasks/Futures: ``(done, pending)``.
508
509   Usage::
510
511        done, pending = await asyncio.wait(aws)
512
513   *timeout* (a float or int), if specified, can be used to control
514   the maximum number of seconds to wait before returning.
515
516   Note that this function does not raise :exc:`asyncio.TimeoutError`.
517   Futures or Tasks that aren't done when the timeout occurs are simply
518   returned in the second set.
519
520   *return_when* indicates when this function should return.  It must
521   be one of the following constants:
522
523   .. tabularcolumns:: |l|L|
524
525   +-----------------------------+----------------------------------------+
526   | Constant                    | Description                            |
527   +=============================+========================================+
528   | :const:`FIRST_COMPLETED`    | The function will return when any      |
529   |                             | future finishes or is cancelled.       |
530   +-----------------------------+----------------------------------------+
531   | :const:`FIRST_EXCEPTION`    | The function will return when any      |
532   |                             | future finishes by raising an          |
533   |                             | exception.  If no future raises an     |
534   |                             | exception then it is equivalent to     |
535   |                             | :const:`ALL_COMPLETED`.                |
536   +-----------------------------+----------------------------------------+
537   | :const:`ALL_COMPLETED`      | The function will return when all      |
538   |                             | futures finish or are cancelled.       |
539   +-----------------------------+----------------------------------------+
540
541   Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
542   futures when a timeout occurs.
543
544   .. deprecated:: 3.8
545
546      If any awaitable in *aws* is a coroutine, it is automatically
547      scheduled as a Task.  Passing coroutines objects to
548      ``wait()`` directly is deprecated as it leads to
549      :ref:`confusing behavior <asyncio_example_wait_coroutine>`.
550
551   .. deprecated-removed:: 3.8 3.10
552
553      The *loop* parameter.
554
555   .. _asyncio_example_wait_coroutine:
556   .. note::
557
558      ``wait()`` schedules coroutines as Tasks automatically and later
559      returns those implicitly created Task objects in ``(done, pending)``
560      sets.  Therefore the following code won't work as expected::
561
562          async def foo():
563              return 42
564
565          coro = foo()
566          done, pending = await asyncio.wait({coro})
567
568          if coro in done:
569              # This branch will never be run!
570
571      Here is how the above snippet can be fixed::
572
573          async def foo():
574              return 42
575
576          task = asyncio.create_task(foo())
577          done, pending = await asyncio.wait({task})
578
579          if task in done:
580              # Everything will work as expected now.
581
582   .. deprecated:: 3.8
583
584      Passing coroutine objects to ``wait()`` directly is
585      deprecated.
586
587
588.. function:: as_completed(aws, \*, loop=None, timeout=None)
589
590   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
591   set concurrently.  Return an iterator of coroutines.
592   Each coroutine returned can be awaited to get the earliest next
593   result from the set of the remaining awaitables.
594
595   Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
596   all Futures are done.
597
598   .. deprecated-removed:: 3.8 3.10
599      The *loop* parameter.
600
601   Example::
602
603       for coro in as_completed(aws):
604           earliest_result = await coro
605           # ...
606
607
608Scheduling From Other Threads
609=============================
610
611.. function:: run_coroutine_threadsafe(coro, loop)
612
613   Submit a coroutine to the given event loop.  Thread-safe.
614
615   Return a :class:`concurrent.futures.Future` to wait for the result
616   from another OS thread.
617
618   This function is meant to be called from a different OS thread
619   than the one where the event loop is running.  Example::
620
621     # Create a coroutine
622     coro = asyncio.sleep(1, result=3)
623
624     # Submit the coroutine to a given loop
625     future = asyncio.run_coroutine_threadsafe(coro, loop)
626
627     # Wait for the result with an optional timeout argument
628     assert future.result(timeout) == 3
629
630   If an exception is raised in the coroutine, the returned Future
631   will be notified.  It can also be used to cancel the task in
632   the event loop::
633
634     try:
635         result = future.result(timeout)
636     except asyncio.TimeoutError:
637         print('The coroutine took too long, cancelling the task...')
638         future.cancel()
639     except Exception as exc:
640         print(f'The coroutine raised an exception: {exc!r}')
641     else:
642         print(f'The coroutine returned: {result!r}')
643
644   See the :ref:`concurrency and multithreading <asyncio-multithreading>`
645   section of the documentation.
646
647   Unlike other asyncio functions this function requires the *loop*
648   argument to be passed explicitly.
649
650   .. versionadded:: 3.5.1
651
652
653Introspection
654=============
655
656
657.. function:: current_task(loop=None)
658
659   Return the currently running :class:`Task` instance, or ``None`` if
660   no task is running.
661
662   If *loop* is ``None`` :func:`get_running_loop` is used to get
663   the current loop.
664
665   .. versionadded:: 3.7
666
667
668.. function:: all_tasks(loop=None)
669
670   Return a set of not yet finished :class:`Task` objects run by
671   the loop.
672
673   If *loop* is ``None``, :func:`get_running_loop` is used for getting
674   current loop.
675
676   .. versionadded:: 3.7
677
678
679Task Object
680===========
681
682.. class:: Task(coro, \*, loop=None, name=None)
683
684   A :class:`Future-like <Future>` object that runs a Python
685   :ref:`coroutine <coroutine>`.  Not thread-safe.
686
687   Tasks are used to run coroutines in event loops.
688   If a coroutine awaits on a Future, the Task suspends
689   the execution of the coroutine and waits for the completion
690   of the Future.  When the Future is *done*, the execution of
691   the wrapped coroutine resumes.
692
693   Event loops use cooperative scheduling: an event loop runs
694   one Task at a time.  While a Task awaits for the completion of a
695   Future, the event loop runs other Tasks, callbacks, or performs
696   IO operations.
697
698   Use the high-level :func:`asyncio.create_task` function to create
699   Tasks, or the low-level :meth:`loop.create_task` or
700   :func:`ensure_future` functions.  Manual instantiation of Tasks
701   is discouraged.
702
703   To cancel a running Task use the :meth:`cancel` method.  Calling it
704   will cause the Task to throw a :exc:`CancelledError` exception into
705   the wrapped coroutine.  If a coroutine is awaiting on a Future
706   object during cancellation, the Future object will be cancelled.
707
708   :meth:`cancelled` can be used to check if the Task was cancelled.
709   The method returns ``True`` if the wrapped coroutine did not
710   suppress the :exc:`CancelledError` exception and was actually
711   cancelled.
712
713   :class:`asyncio.Task` inherits from :class:`Future` all of its
714   APIs except :meth:`Future.set_result` and
715   :meth:`Future.set_exception`.
716
717   Tasks support the :mod:`contextvars` module.  When a Task
718   is created it copies the current context and later runs its
719   coroutine in the copied context.
720
721   .. versionchanged:: 3.7
722      Added support for the :mod:`contextvars` module.
723
724   .. versionchanged:: 3.8
725      Added the ``name`` parameter.
726
727   .. deprecated-removed:: 3.8 3.10
728      The *loop* parameter.
729
730   .. method:: cancel()
731
732      Request the Task to be cancelled.
733
734      This arranges for a :exc:`CancelledError` exception to be thrown
735      into the wrapped coroutine on the next cycle of the event loop.
736
737      The coroutine then has a chance to clean up or even deny the
738      request by suppressing the exception with a :keyword:`try` ...
739      ... ``except CancelledError`` ... :keyword:`finally` block.
740      Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
741      not guarantee that the Task will be cancelled, although
742      suppressing cancellation completely is not common and is actively
743      discouraged.
744
745      .. _asyncio_example_task_cancel:
746
747      The following example illustrates how coroutines can intercept
748      the cancellation request::
749
750          async def cancel_me():
751              print('cancel_me(): before sleep')
752
753              try:
754                  # Wait for 1 hour
755                  await asyncio.sleep(3600)
756              except asyncio.CancelledError:
757                  print('cancel_me(): cancel sleep')
758                  raise
759              finally:
760                  print('cancel_me(): after sleep')
761
762          async def main():
763              # Create a "cancel_me" Task
764              task = asyncio.create_task(cancel_me())
765
766              # Wait for 1 second
767              await asyncio.sleep(1)
768
769              task.cancel()
770              try:
771                  await task
772              except asyncio.CancelledError:
773                  print("main(): cancel_me is cancelled now")
774
775          asyncio.run(main())
776
777          # Expected output:
778          #
779          #     cancel_me(): before sleep
780          #     cancel_me(): cancel sleep
781          #     cancel_me(): after sleep
782          #     main(): cancel_me is cancelled now
783
784   .. method:: cancelled()
785
786      Return ``True`` if the Task is *cancelled*.
787
788      The Task is *cancelled* when the cancellation was requested with
789      :meth:`cancel` and the wrapped coroutine propagated the
790      :exc:`CancelledError` exception thrown into it.
791
792   .. method:: done()
793
794      Return ``True`` if the Task is *done*.
795
796      A Task is *done* when the wrapped coroutine either returned
797      a value, raised an exception, or the Task was cancelled.
798
799   .. method:: result()
800
801      Return the result of the Task.
802
803      If the Task is *done*, the result of the wrapped coroutine
804      is returned (or if the coroutine raised an exception, that
805      exception is re-raised.)
806
807      If the Task has been *cancelled*, this method raises
808      a :exc:`CancelledError` exception.
809
810      If the Task's result isn't yet available, this method raises
811      a :exc:`InvalidStateError` exception.
812
813   .. method:: exception()
814
815      Return the exception of the Task.
816
817      If the wrapped coroutine raised an exception that exception
818      is returned.  If the wrapped coroutine returned normally
819      this method returns ``None``.
820
821      If the Task has been *cancelled*, this method raises a
822      :exc:`CancelledError` exception.
823
824      If the Task isn't *done* yet, this method raises an
825      :exc:`InvalidStateError` exception.
826
827   .. method:: add_done_callback(callback, *, context=None)
828
829      Add a callback to be run when the Task is *done*.
830
831      This method should only be used in low-level callback-based code.
832
833      See the documentation of :meth:`Future.add_done_callback`
834      for more details.
835
836   .. method:: remove_done_callback(callback)
837
838      Remove *callback* from the callbacks list.
839
840      This method should only be used in low-level callback-based code.
841
842      See the documentation of :meth:`Future.remove_done_callback`
843      for more details.
844
845   .. method:: get_stack(\*, limit=None)
846
847      Return the list of stack frames for this Task.
848
849      If the wrapped coroutine is not done, this returns the stack
850      where it is suspended.  If the coroutine has completed
851      successfully or was cancelled, this returns an empty list.
852      If the coroutine was terminated by an exception, this returns
853      the list of traceback frames.
854
855      The frames are always ordered from oldest to newest.
856
857      Only one stack frame is returned for a suspended coroutine.
858
859      The optional *limit* argument sets the maximum number of frames
860      to return; by default all available frames are returned.
861      The ordering of the returned list differs depending on whether
862      a stack or a traceback is returned: the newest frames of a
863      stack are returned, but the oldest frames of a traceback are
864      returned.  (This matches the behavior of the traceback module.)
865
866   .. method:: print_stack(\*, limit=None, file=None)
867
868      Print the stack or traceback for this Task.
869
870      This produces output similar to that of the traceback module
871      for the frames retrieved by :meth:`get_stack`.
872
873      The *limit* argument is passed to :meth:`get_stack` directly.
874
875      The *file* argument is an I/O stream to which the output
876      is written; by default output is written to :data:`sys.stderr`.
877
878   .. method:: get_coro()
879
880      Return the coroutine object wrapped by the :class:`Task`.
881
882      .. versionadded:: 3.8
883
884   .. method:: get_name()
885
886      Return the name of the Task.
887
888      If no name has been explicitly assigned to the Task, the default
889      asyncio Task implementation generates a default name during
890      instantiation.
891
892      .. versionadded:: 3.8
893
894   .. method:: set_name(value)
895
896      Set the name of the Task.
897
898      The *value* argument can be any object, which is then
899      converted to a string.
900
901      In the default Task implementation, the name will be visible
902      in the :func:`repr` output of a task object.
903
904      .. versionadded:: 3.8
905
906   .. classmethod:: all_tasks(loop=None)
907
908      Return a set of all tasks for an event loop.
909
910      By default all tasks for the current event loop are returned.
911      If *loop* is ``None``, the :func:`get_event_loop` function
912      is used to get the current loop.
913
914      .. deprecated-removed:: 3.7 3.9
915
916         Do not call this as a task method. Use the :func:`asyncio.all_tasks`
917         function instead.
918
919   .. classmethod:: current_task(loop=None)
920
921      Return the currently running task or ``None``.
922
923      If *loop* is ``None``, the :func:`get_event_loop` function
924      is used to get the current loop.
925
926      .. deprecated-removed:: 3.7 3.9
927
928         Do not call this as a task method.  Use the
929         :func:`asyncio.current_task` function instead.
930
931
932.. _asyncio_generator_based_coro:
933
934Generator-based Coroutines
935==========================
936
937.. note::
938
939   Support for generator-based coroutines is **deprecated** and
940   is scheduled for removal in Python 3.10.
941
942Generator-based coroutines predate async/await syntax.  They are
943Python generators that use ``yield from`` expressions to await
944on Futures and other coroutines.
945
946Generator-based coroutines should be decorated with
947:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
948enforced.
949
950
951.. decorator:: coroutine
952
953    Decorator to mark generator-based coroutines.
954
955    This decorator enables legacy generator-based coroutines to be
956    compatible with async/await code::
957
958        @asyncio.coroutine
959        def old_style_coroutine():
960            yield from asyncio.sleep(1)
961
962        async def main():
963            await old_style_coroutine()
964
965    This decorator should not be used for :keyword:`async def`
966    coroutines.
967
968    .. deprecated-removed:: 3.8 3.10
969
970       Use :keyword:`async def` instead.
971
972.. function:: iscoroutine(obj)
973
974   Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
975
976   This method is different from :func:`inspect.iscoroutine` because
977   it returns ``True`` for generator-based coroutines.
978
979.. function:: iscoroutinefunction(func)
980
981   Return ``True`` if *func* is a :ref:`coroutine function
982   <coroutine>`.
983
984   This method is different from :func:`inspect.iscoroutinefunction`
985   because it returns ``True`` for generator-based coroutine functions
986   decorated with :func:`@coroutine <coroutine>`.
987