• 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**Source code:** :source:`Lib/asyncio/coroutines.py`
22
23----------------------------------------------------
24
25:term:`Coroutines <coroutine>` declared with the async/await syntax is the
26preferred way of writing asyncio applications.  For example, the following
27snippet of code prints "hello", waits 1 second,
28and then prints "world"::
29
30    >>> import asyncio
31
32    >>> async def main():
33    ...     print('hello')
34    ...     await asyncio.sleep(1)
35    ...     print('world')
36
37    >>> asyncio.run(main())
38    hello
39    world
40
41Note that simply calling a coroutine will not schedule it to
42be executed::
43
44    >>> main()
45    <coroutine object main at 0x1053bb7c8>
46
47To actually run a coroutine, asyncio provides the following mechanisms:
48
49* The :func:`asyncio.run` function to run the top-level
50  entry point "main()" function (see the above example.)
51
52* Awaiting on a coroutine.  The following snippet of code will
53  print "hello" after waiting for 1 second, and then print "world"
54  after waiting for *another* 2 seconds::
55
56      import asyncio
57      import time
58
59      async def say_after(delay, what):
60          await asyncio.sleep(delay)
61          print(what)
62
63      async def main():
64          print(f"started at {time.strftime('%X')}")
65
66          await say_after(1, 'hello')
67          await say_after(2, 'world')
68
69          print(f"finished at {time.strftime('%X')}")
70
71      asyncio.run(main())
72
73  Expected output::
74
75      started at 17:13:52
76      hello
77      world
78      finished at 17:13:55
79
80* The :func:`asyncio.create_task` function to run coroutines
81  concurrently as asyncio :class:`Tasks <Task>`.
82
83  Let's modify the above example and run two ``say_after`` coroutines
84  *concurrently*::
85
86      async def main():
87          task1 = asyncio.create_task(
88              say_after(1, 'hello'))
89
90          task2 = asyncio.create_task(
91              say_after(2, 'world'))
92
93          print(f"started at {time.strftime('%X')}")
94
95          # Wait until both tasks are completed (should take
96          # around 2 seconds.)
97          await task1
98          await task2
99
100          print(f"finished at {time.strftime('%X')}")
101
102  Note that expected output now shows that the snippet runs
103  1 second faster than before::
104
105      started at 17:14:32
106      hello
107      world
108      finished at 17:14:34
109
110* The :class:`asyncio.TaskGroup` class provides a more modern
111  alternative to :func:`create_task`.
112  Using this API, the last example becomes::
113
114      async def main():
115          async with asyncio.TaskGroup() as tg:
116              task1 = tg.create_task(
117                  say_after(1, 'hello'))
118
119              task2 = tg.create_task(
120                  say_after(2, 'world'))
121
122              print(f"started at {time.strftime('%X')}")
123
124          # The await is implicit when the context manager exits.
125
126          print(f"finished at {time.strftime('%X')}")
127
128  The timing and output should be the same as for the previous version.
129
130  .. versionadded:: 3.11
131     :class:`asyncio.TaskGroup`.
132
133
134.. _asyncio-awaitables:
135
136Awaitables
137==========
138
139We say that an object is an **awaitable** object if it can be used
140in an :keyword:`await` expression.  Many asyncio APIs are designed to
141accept awaitables.
142
143There are three main types of *awaitable* objects:
144**coroutines**, **Tasks**, and **Futures**.
145
146
147.. rubric:: Coroutines
148
149Python coroutines are *awaitables* and therefore can be awaited from
150other coroutines::
151
152    import asyncio
153
154    async def nested():
155        return 42
156
157    async def main():
158        # Nothing happens if we just call "nested()".
159        # A coroutine object is created but not awaited,
160        # so it *won't run at all*.
161        nested()  # will raise a "RuntimeWarning".
162
163        # Let's do it differently now and await it:
164        print(await nested())  # will print "42".
165
166    asyncio.run(main())
167
168.. important::
169
170   In this documentation the term "coroutine" can be used for
171   two closely related concepts:
172
173   * a *coroutine function*: an :keyword:`async def` function;
174
175   * a *coroutine object*: an object returned by calling a
176     *coroutine function*.
177
178
179.. rubric:: Tasks
180
181*Tasks* are used to schedule coroutines *concurrently*.
182
183When a coroutine is wrapped into a *Task* with functions like
184:func:`asyncio.create_task` the coroutine is automatically
185scheduled to run soon::
186
187    import asyncio
188
189    async def nested():
190        return 42
191
192    async def main():
193        # Schedule nested() to run soon concurrently
194        # with "main()".
195        task = asyncio.create_task(nested())
196
197        # "task" can now be used to cancel "nested()", or
198        # can simply be awaited to wait until it is complete:
199        await task
200
201    asyncio.run(main())
202
203
204.. rubric:: Futures
205
206A :class:`Future` is a special **low-level** awaitable object that
207represents an **eventual result** of an asynchronous operation.
208
209When a Future object is *awaited* it means that the coroutine will
210wait until the Future is resolved in some other place.
211
212Future objects in asyncio are needed to allow callback-based code
213to be used with async/await.
214
215Normally **there is no need** to create Future objects at the
216application level code.
217
218Future objects, sometimes exposed by libraries and some asyncio
219APIs, can be awaited::
220
221    async def main():
222        await function_that_returns_a_future_object()
223
224        # this is also valid:
225        await asyncio.gather(
226            function_that_returns_a_future_object(),
227            some_python_coroutine()
228        )
229
230A good example of a low-level function that returns a Future object
231is :meth:`loop.run_in_executor`.
232
233
234Creating Tasks
235==============
236
237**Source code:** :source:`Lib/asyncio/tasks.py`
238
239-----------------------------------------------
240
241.. function:: create_task(coro, *, name=None, context=None)
242
243   Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
244   and schedule its execution.  Return the Task object.
245
246   If *name* is not ``None``, it is set as the name of the task using
247   :meth:`Task.set_name`.
248
249   An optional keyword-only *context* argument allows specifying a
250   custom :class:`contextvars.Context` for the *coro* to run in.
251   The current context copy is created when no *context* is provided.
252
253   The task is executed in the loop returned by :func:`get_running_loop`,
254   :exc:`RuntimeError` is raised if there is no running loop in
255   current thread.
256
257   .. note::
258
259      :meth:`asyncio.TaskGroup.create_task` is a new alternative
260      leveraging structural concurrency; it allows for waiting
261      for a group of related tasks with strong safety guarantees.
262
263   .. important::
264
265      Save a reference to the result of this function, to avoid
266      a task disappearing mid-execution. The event loop only keeps
267      weak references to tasks. A task that isn't referenced elsewhere
268      may get garbage collected at any time, even before it's done.
269      For reliable "fire-and-forget" background tasks, gather them in
270      a collection::
271
272          background_tasks = set()
273
274          for i in range(10):
275              task = asyncio.create_task(some_coro(param=i))
276
277              # Add task to the set. This creates a strong reference.
278              background_tasks.add(task)
279
280              # To prevent keeping references to finished tasks forever,
281              # make each task remove its own reference from the set after
282              # completion:
283              task.add_done_callback(background_tasks.discard)
284
285   .. versionadded:: 3.7
286
287   .. versionchanged:: 3.8
288      Added the *name* parameter.
289
290   .. versionchanged:: 3.11
291      Added the *context* parameter.
292
293
294Task Cancellation
295=================
296
297Tasks can easily and safely be cancelled.
298When a task is cancelled, :exc:`asyncio.CancelledError` will be raised
299in the task at the next opportunity.
300
301It is recommended that coroutines use ``try/finally`` blocks to robustly
302perform clean-up logic. In case :exc:`asyncio.CancelledError`
303is explicitly caught, it should generally be propagated when
304clean-up is complete. :exc:`asyncio.CancelledError` directly subclasses
305:exc:`BaseException` so most code will not need to be aware of it.
306
307The asyncio components that enable structured concurrency, like
308:class:`asyncio.TaskGroup` and :func:`asyncio.timeout`,
309are implemented using cancellation internally and might misbehave if
310a coroutine swallows :exc:`asyncio.CancelledError`. Similarly, user code
311should not generally call :meth:`uncancel <asyncio.Task.uncancel>`.
312However, in cases when suppressing :exc:`asyncio.CancelledError` is
313truly desired, it is necessary to also call ``uncancel()`` to completely
314remove the cancellation state.
315
316.. _taskgroups:
317
318Task Groups
319===========
320
321Task groups combine a task creation API with a convenient
322and reliable way to wait for all tasks in the group to finish.
323
324.. class:: TaskGroup()
325
326   An :ref:`asynchronous context manager <async-context-managers>`
327   holding a group of tasks.
328   Tasks can be added to the group using :meth:`create_task`.
329   All tasks are awaited when the context manager exits.
330
331   .. versionadded:: 3.11
332
333   .. method:: create_task(coro, *, name=None, context=None)
334
335      Create a task in this task group.
336      The signature matches that of :func:`asyncio.create_task`.
337      If the task group is inactive (e.g. not yet entered,
338      already finished, or in the process of shutting down),
339      we will close the given ``coro``.
340
341      .. versionchanged:: 3.13
342
343         Close the given coroutine if the task group is not active.
344
345Example::
346
347    async def main():
348        async with asyncio.TaskGroup() as tg:
349            task1 = tg.create_task(some_coro(...))
350            task2 = tg.create_task(another_coro(...))
351        print(f"Both tasks have completed now: {task1.result()}, {task2.result()}")
352
353The ``async with`` statement will wait for all tasks in the group to finish.
354While waiting, new tasks may still be added to the group
355(for example, by passing ``tg`` into one of the coroutines
356and calling ``tg.create_task()`` in that coroutine).
357Once the last task has finished and the ``async with`` block is exited,
358no new tasks may be added to the group.
359
360The first time any of the tasks belonging to the group fails
361with an exception other than :exc:`asyncio.CancelledError`,
362the remaining tasks in the group are cancelled.
363No further tasks can then be added to the group.
364At this point, if the body of the ``async with`` statement is still active
365(i.e., :meth:`~object.__aexit__` hasn't been called yet),
366the task directly containing the ``async with`` statement is also cancelled.
367The resulting :exc:`asyncio.CancelledError` will interrupt an ``await``,
368but it will not bubble out of the containing ``async with`` statement.
369
370Once all tasks have finished, if any tasks have failed
371with an exception other than :exc:`asyncio.CancelledError`,
372those exceptions are combined in an
373:exc:`ExceptionGroup` or :exc:`BaseExceptionGroup`
374(as appropriate; see their documentation)
375which is then raised.
376
377Two base exceptions are treated specially:
378If any task fails with :exc:`KeyboardInterrupt` or :exc:`SystemExit`,
379the task group still cancels the remaining tasks and waits for them,
380but then the initial :exc:`KeyboardInterrupt` or :exc:`SystemExit`
381is re-raised instead of :exc:`ExceptionGroup` or :exc:`BaseExceptionGroup`.
382
383If the body of the ``async with`` statement exits with an exception
384(so :meth:`~object.__aexit__` is called with an exception set),
385this is treated the same as if one of the tasks failed:
386the remaining tasks are cancelled and then waited for,
387and non-cancellation exceptions are grouped into an
388exception group and raised.
389The exception passed into :meth:`~object.__aexit__`,
390unless it is :exc:`asyncio.CancelledError`,
391is also included in the exception group.
392The same special case is made for
393:exc:`KeyboardInterrupt` and :exc:`SystemExit` as in the previous paragraph.
394
395Task groups are careful not to mix up the internal cancellation used to
396"wake up" their :meth:`~object.__aexit__` with cancellation requests
397for the task in which they are running made by other parties.
398In particular, when one task group is syntactically nested in another,
399and both experience an exception in one of their child tasks simultaneously,
400the inner task group will process its exceptions, and then the outer task group
401will receive another cancellation and process its own exceptions.
402
403In the case where a task group is cancelled externally and also must
404raise an :exc:`ExceptionGroup`, it will call the parent task's
405:meth:`~asyncio.Task.cancel` method. This ensures that a
406:exc:`asyncio.CancelledError` will be raised at the next
407:keyword:`await`, so the cancellation is not lost.
408
409Task groups preserve the cancellation count
410reported by :meth:`asyncio.Task.cancelling`.
411
412.. versionchanged:: 3.13
413
414   Improved handling of simultaneous internal and external cancellations
415   and correct preservation of cancellation counts.
416
417Terminating a Task Group
418------------------------
419
420While terminating a task group is not natively supported by the standard
421library, termination can be achieved by adding an exception-raising task
422to the task group and ignoring the raised exception:
423
424.. code-block:: python
425
426   import asyncio
427   from asyncio import TaskGroup
428
429   class TerminateTaskGroup(Exception):
430       """Exception raised to terminate a task group."""
431
432   async def force_terminate_task_group():
433       """Used to force termination of a task group."""
434       raise TerminateTaskGroup()
435
436   async def job(task_id, sleep_time):
437       print(f'Task {task_id}: start')
438       await asyncio.sleep(sleep_time)
439       print(f'Task {task_id}: done')
440
441   async def main():
442       try:
443           async with TaskGroup() as group:
444               # spawn some tasks
445               group.create_task(job(1, 0.5))
446               group.create_task(job(2, 1.5))
447               # sleep for 1 second
448               await asyncio.sleep(1)
449               # add an exception-raising task to force the group to terminate
450               group.create_task(force_terminate_task_group())
451       except* TerminateTaskGroup:
452           pass
453
454   asyncio.run(main())
455
456Expected output:
457
458.. code-block:: text
459
460   Task 1: start
461   Task 2: start
462   Task 1: done
463
464Sleeping
465========
466
467.. coroutinefunction:: sleep(delay, result=None)
468
469   Block for *delay* seconds.
470
471   If *result* is provided, it is returned to the caller
472   when the coroutine completes.
473
474   ``sleep()`` always suspends the current task, allowing other tasks
475   to run.
476
477   Setting the delay to 0 provides an optimized path to allow other
478   tasks to run. This can be used by long-running functions to avoid
479   blocking the event loop for the full duration of the function call.
480
481   .. _asyncio_example_sleep:
482
483   Example of coroutine displaying the current date every second
484   for 5 seconds::
485
486    import asyncio
487    import datetime
488
489    async def display_date():
490        loop = asyncio.get_running_loop()
491        end_time = loop.time() + 5.0
492        while True:
493            print(datetime.datetime.now())
494            if (loop.time() + 1.0) >= end_time:
495                break
496            await asyncio.sleep(1)
497
498    asyncio.run(display_date())
499
500
501   .. versionchanged:: 3.10
502      Removed the *loop* parameter.
503
504   .. versionchanged:: 3.13
505      Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
506
507
508Running Tasks Concurrently
509==========================
510
511.. awaitablefunction:: gather(*aws, return_exceptions=False)
512
513   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
514   sequence *concurrently*.
515
516   If any awaitable in *aws* is a coroutine, it is automatically
517   scheduled as a Task.
518
519   If all awaitables are completed successfully, the result is an
520   aggregate list of returned values.  The order of result values
521   corresponds to the order of awaitables in *aws*.
522
523   If *return_exceptions* is ``False`` (default), the first
524   raised exception is immediately propagated to the task that
525   awaits on ``gather()``.  Other awaitables in the *aws* sequence
526   **won't be cancelled** and will continue to run.
527
528   If *return_exceptions* is ``True``, exceptions are treated the
529   same as successful results, and aggregated in the result list.
530
531   If ``gather()`` is *cancelled*, all submitted awaitables
532   (that have not completed yet) are also *cancelled*.
533
534   If any Task or Future from the *aws* sequence is *cancelled*, it is
535   treated as if it raised :exc:`CancelledError` -- the ``gather()``
536   call is **not** cancelled in this case.  This is to prevent the
537   cancellation of one submitted Task/Future to cause other
538   Tasks/Futures to be cancelled.
539
540   .. note::
541      A new alternative to create and run tasks concurrently and
542      wait for their completion is :class:`asyncio.TaskGroup`. *TaskGroup*
543      provides stronger safety guarantees than *gather* for scheduling a nesting of subtasks:
544      if a task (or a subtask, a task scheduled by a task)
545      raises an exception, *TaskGroup* will, while *gather* will not,
546      cancel the remaining scheduled tasks).
547
548   .. _asyncio_example_gather:
549
550   Example::
551
552      import asyncio
553
554      async def factorial(name, number):
555          f = 1
556          for i in range(2, number + 1):
557              print(f"Task {name}: Compute factorial({number}), currently i={i}...")
558              await asyncio.sleep(1)
559              f *= i
560          print(f"Task {name}: factorial({number}) = {f}")
561          return f
562
563      async def main():
564          # Schedule three calls *concurrently*:
565          L = await asyncio.gather(
566              factorial("A", 2),
567              factorial("B", 3),
568              factorial("C", 4),
569          )
570          print(L)
571
572      asyncio.run(main())
573
574      # Expected output:
575      #
576      #     Task A: Compute factorial(2), currently i=2...
577      #     Task B: Compute factorial(3), currently i=2...
578      #     Task C: Compute factorial(4), currently i=2...
579      #     Task A: factorial(2) = 2
580      #     Task B: Compute factorial(3), currently i=3...
581      #     Task C: Compute factorial(4), currently i=3...
582      #     Task B: factorial(3) = 6
583      #     Task C: Compute factorial(4), currently i=4...
584      #     Task C: factorial(4) = 24
585      #     [2, 6, 24]
586
587   .. note::
588      If *return_exceptions* is false, cancelling gather() after it
589      has been marked done won't cancel any submitted awaitables.
590      For instance, gather can be marked done after propagating an
591      exception to the caller, therefore, calling ``gather.cancel()``
592      after catching an exception (raised by one of the awaitables) from
593      gather won't cancel any other awaitables.
594
595   .. versionchanged:: 3.7
596      If the *gather* itself is cancelled, the cancellation is
597      propagated regardless of *return_exceptions*.
598
599   .. versionchanged:: 3.10
600      Removed the *loop* parameter.
601
602   .. deprecated:: 3.10
603      Deprecation warning is emitted if no positional arguments are provided
604      or not all positional arguments are Future-like objects
605      and there is no running event loop.
606
607
608.. _eager-task-factory:
609
610Eager Task Factory
611==================
612
613.. function:: eager_task_factory(loop, coro, *, name=None, context=None)
614
615    A task factory for eager task execution.
616
617    When using this factory (via :meth:`loop.set_task_factory(asyncio.eager_task_factory) <loop.set_task_factory>`),
618    coroutines begin execution synchronously during :class:`Task` construction.
619    Tasks are only scheduled on the event loop if they block.
620    This can be a performance improvement as the overhead of loop scheduling
621    is avoided for coroutines that complete synchronously.
622
623    A common example where this is beneficial is coroutines which employ
624    caching or memoization to avoid actual I/O when possible.
625
626    .. note::
627
628        Immediate execution of the coroutine is a semantic change.
629        If the coroutine returns or raises, the task is never scheduled
630        to the event loop. If the coroutine execution blocks, the task is
631        scheduled to the event loop. This change may introduce behavior
632        changes to existing applications. For example,
633        the application's task execution order is likely to change.
634
635    .. versionadded:: 3.12
636
637.. function:: create_eager_task_factory(custom_task_constructor)
638
639    Create an eager task factory, similar to :func:`eager_task_factory`,
640    using the provided *custom_task_constructor* when creating a new task instead
641    of the default :class:`Task`.
642
643    *custom_task_constructor* must be a *callable* with the signature matching
644    the signature of :class:`Task.__init__ <Task>`.
645    The callable must return a :class:`asyncio.Task`-compatible object.
646
647    This function returns a *callable* intended to be used as a task factory of an
648    event loop via :meth:`loop.set_task_factory(factory) <loop.set_task_factory>`).
649
650    .. versionadded:: 3.12
651
652
653Shielding From Cancellation
654===========================
655
656.. awaitablefunction:: shield(aw)
657
658   Protect an :ref:`awaitable object <asyncio-awaitables>`
659   from being :meth:`cancelled <Task.cancel>`.
660
661   If *aw* is a coroutine it is automatically scheduled as a Task.
662
663   The statement::
664
665       task = asyncio.create_task(something())
666       res = await shield(task)
667
668   is equivalent to::
669
670       res = await something()
671
672   *except* that if the coroutine containing it is cancelled, the
673   Task running in ``something()`` is not cancelled.  From the point
674   of view of ``something()``, the cancellation did not happen.
675   Although its caller is still cancelled, so the "await" expression
676   still raises a :exc:`CancelledError`.
677
678   If ``something()`` is cancelled by other means (i.e. from within
679   itself) that would also cancel ``shield()``.
680
681   If it is desired to completely ignore cancellation (not recommended)
682   the ``shield()`` function should be combined with a try/except
683   clause, as follows::
684
685       task = asyncio.create_task(something())
686       try:
687           res = await shield(task)
688       except CancelledError:
689           res = None
690
691   .. important::
692
693      Save a reference to tasks passed to this function, to avoid
694      a task disappearing mid-execution. The event loop only keeps
695      weak references to tasks. A task that isn't referenced elsewhere
696      may get garbage collected at any time, even before it's done.
697
698   .. versionchanged:: 3.10
699      Removed the *loop* parameter.
700
701   .. deprecated:: 3.10
702      Deprecation warning is emitted if *aw* is not Future-like object
703      and there is no running event loop.
704
705
706Timeouts
707========
708
709.. function:: timeout(delay)
710
711    Return an :ref:`asynchronous context manager <async-context-managers>`
712    that can be used to limit the amount of time spent waiting on
713    something.
714
715    *delay* can either be ``None``, or a float/int number of
716    seconds to wait. If *delay* is ``None``, no time limit will
717    be applied; this can be useful if the delay is unknown when
718    the context manager is created.
719
720    In either case, the context manager can be rescheduled after
721    creation using :meth:`Timeout.reschedule`.
722
723    Example::
724
725        async def main():
726            async with asyncio.timeout(10):
727                await long_running_task()
728
729    If ``long_running_task`` takes more than 10 seconds to complete,
730    the context manager will cancel the current task and handle
731    the resulting :exc:`asyncio.CancelledError` internally, transforming it
732    into a :exc:`TimeoutError` which can be caught and handled.
733
734    .. note::
735
736      The :func:`asyncio.timeout` context manager is what transforms
737      the :exc:`asyncio.CancelledError` into a :exc:`TimeoutError`,
738      which means the :exc:`TimeoutError` can only be caught
739      *outside* of the context manager.
740
741    Example of catching :exc:`TimeoutError`::
742
743        async def main():
744            try:
745                async with asyncio.timeout(10):
746                    await long_running_task()
747            except TimeoutError:
748                print("The long operation timed out, but we've handled it.")
749
750            print("This statement will run regardless.")
751
752    The context manager produced by :func:`asyncio.timeout` can be
753    rescheduled to a different deadline and inspected.
754
755    .. class:: Timeout(when)
756
757       An :ref:`asynchronous context manager <async-context-managers>`
758       for cancelling overdue coroutines.
759
760       ``when`` should be an absolute time at which the context should time out,
761       as measured by the event loop's clock:
762
763       - If ``when`` is ``None``, the timeout will never trigger.
764       - If ``when < loop.time()``, the timeout will trigger on the next
765         iteration of the event loop.
766
767        .. method:: when() -> float | None
768
769           Return the current deadline, or ``None`` if the current
770           deadline is not set.
771
772        .. method:: reschedule(when: float | None)
773
774            Reschedule the timeout.
775
776        .. method:: expired() -> bool
777
778           Return whether the context manager has exceeded its deadline
779           (expired).
780
781    Example::
782
783        async def main():
784            try:
785                # We do not know the timeout when starting, so we pass ``None``.
786                async with asyncio.timeout(None) as cm:
787                    # We know the timeout now, so we reschedule it.
788                    new_deadline = get_running_loop().time() + 10
789                    cm.reschedule(new_deadline)
790
791                    await long_running_task()
792            except TimeoutError:
793                pass
794
795            if cm.expired():
796                print("Looks like we haven't finished on time.")
797
798    Timeout context managers can be safely nested.
799
800    .. versionadded:: 3.11
801
802.. function:: timeout_at(when)
803
804   Similar to :func:`asyncio.timeout`, except *when* is the absolute time
805   to stop waiting, or ``None``.
806
807   Example::
808
809      async def main():
810          loop = get_running_loop()
811          deadline = loop.time() + 20
812          try:
813              async with asyncio.timeout_at(deadline):
814                  await long_running_task()
815          except TimeoutError:
816              print("The long operation timed out, but we've handled it.")
817
818          print("This statement will run regardless.")
819
820   .. versionadded:: 3.11
821
822.. coroutinefunction:: wait_for(aw, timeout)
823
824   Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
825   to complete with a timeout.
826
827   If *aw* is a coroutine it is automatically scheduled as a Task.
828
829   *timeout* can either be ``None`` or a float or int number of seconds
830   to wait for.  If *timeout* is ``None``, block until the future
831   completes.
832
833   If a timeout occurs, it cancels the task and raises
834   :exc:`TimeoutError`.
835
836   To avoid the task :meth:`cancellation <Task.cancel>`,
837   wrap it in :func:`shield`.
838
839   The function will wait until the future is actually cancelled,
840   so the total wait time may exceed the *timeout*. If an exception
841   happens during cancellation, it is propagated.
842
843   If the wait is cancelled, the future *aw* is also cancelled.
844
845   .. _asyncio_example_waitfor:
846
847   Example::
848
849       async def eternity():
850           # Sleep for one hour
851           await asyncio.sleep(3600)
852           print('yay!')
853
854       async def main():
855           # Wait for at most 1 second
856           try:
857               await asyncio.wait_for(eternity(), timeout=1.0)
858           except TimeoutError:
859               print('timeout!')
860
861       asyncio.run(main())
862
863       # Expected output:
864       #
865       #     timeout!
866
867   .. versionchanged:: 3.7
868      When *aw* is cancelled due to a timeout, ``wait_for`` waits
869      for *aw* to be cancelled.  Previously, it raised
870      :exc:`TimeoutError` immediately.
871
872   .. versionchanged:: 3.10
873      Removed the *loop* parameter.
874
875   .. versionchanged:: 3.11
876      Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`.
877
878
879Waiting Primitives
880==================
881
882.. coroutinefunction:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
883
884   Run :class:`~asyncio.Future` and :class:`~asyncio.Task` instances in the *aws*
885   iterable concurrently and block until the condition specified
886   by *return_when*.
887
888   The *aws* iterable must not be empty.
889
890   Returns two sets of Tasks/Futures: ``(done, pending)``.
891
892   Usage::
893
894        done, pending = await asyncio.wait(aws)
895
896   *timeout* (a float or int), if specified, can be used to control
897   the maximum number of seconds to wait before returning.
898
899   Note that this function does not raise :exc:`TimeoutError`.
900   Futures or Tasks that aren't done when the timeout occurs are simply
901   returned in the second set.
902
903   *return_when* indicates when this function should return.  It must
904   be one of the following constants:
905
906   .. list-table::
907      :header-rows: 1
908
909      * - Constant
910        - Description
911
912      * - .. data:: FIRST_COMPLETED
913        - The function will return when any future finishes or is cancelled.
914
915      * - .. data:: FIRST_EXCEPTION
916        - The function will return when any future finishes by raising an
917          exception. If no future raises an exception
918          then it is equivalent to :const:`ALL_COMPLETED`.
919
920      * - .. data:: ALL_COMPLETED
921        - The function will return when all futures finish or are cancelled.
922
923   Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
924   futures when a timeout occurs.
925
926   .. versionchanged:: 3.10
927      Removed the *loop* parameter.
928
929   .. versionchanged:: 3.11
930      Passing coroutine objects to ``wait()`` directly is forbidden.
931
932   .. versionchanged:: 3.12
933      Added support for generators yielding tasks.
934
935
936.. function:: as_completed(aws, *, timeout=None)
937
938   Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* iterable
939   concurrently. The returned object can be iterated to obtain the results
940   of the awaitables as they finish.
941
942   The object returned by ``as_completed()`` can be iterated as an
943   :term:`asynchronous iterator` or a plain :term:`iterator`. When asynchronous
944   iteration is used, the originally-supplied awaitables are yielded if they
945   are tasks or futures. This makes it easy to correlate previously-scheduled
946   tasks with their results. Example::
947
948       ipv4_connect = create_task(open_connection("127.0.0.1", 80))
949       ipv6_connect = create_task(open_connection("::1", 80))
950       tasks = [ipv4_connect, ipv6_connect]
951
952       async for earliest_connect in as_completed(tasks):
953           # earliest_connect is done. The result can be obtained by
954           # awaiting it or calling earliest_connect.result()
955           reader, writer = await earliest_connect
956
957           if earliest_connect is ipv6_connect:
958               print("IPv6 connection established.")
959           else:
960               print("IPv4 connection established.")
961
962   During asynchronous iteration, implicitly-created tasks will be yielded for
963   supplied awaitables that aren't tasks or futures.
964
965   When used as a plain iterator, each iteration yields a new coroutine that
966   returns the result or raises the exception of the next completed awaitable.
967   This pattern is compatible with Python versions older than 3.13::
968
969       ipv4_connect = create_task(open_connection("127.0.0.1", 80))
970       ipv6_connect = create_task(open_connection("::1", 80))
971       tasks = [ipv4_connect, ipv6_connect]
972
973       for next_connect in as_completed(tasks):
974           # next_connect is not one of the original task objects. It must be
975           # awaited to obtain the result value or raise the exception of the
976           # awaitable that finishes next.
977           reader, writer = await next_connect
978
979   A :exc:`TimeoutError` is raised if the timeout occurs before all awaitables
980   are done. This is raised by the ``async for`` loop during asynchronous
981   iteration or by the coroutines yielded during plain iteration.
982
983   .. versionchanged:: 3.10
984      Removed the *loop* parameter.
985
986   .. deprecated:: 3.10
987      Deprecation warning is emitted if not all awaitable objects in the *aws*
988      iterable are Future-like objects and there is no running event loop.
989
990   .. versionchanged:: 3.12
991      Added support for generators yielding tasks.
992
993   .. versionchanged:: 3.13
994      The result can now be used as either an :term:`asynchronous iterator`
995      or as a plain :term:`iterator` (previously it was only a plain iterator).
996
997
998Running in Threads
999==================
1000
1001.. coroutinefunction:: to_thread(func, /, *args, **kwargs)
1002
1003   Asynchronously run function *func* in a separate thread.
1004
1005   Any \*args and \*\*kwargs supplied for this function are directly passed
1006   to *func*. Also, the current :class:`contextvars.Context` is propagated,
1007   allowing context variables from the event loop thread to be accessed in the
1008   separate thread.
1009
1010   Return a coroutine that can be awaited to get the eventual result of *func*.
1011
1012   This coroutine function is primarily intended to be used for executing
1013   IO-bound functions/methods that would otherwise block the event loop if
1014   they were run in the main thread. For example::
1015
1016       def blocking_io():
1017           print(f"start blocking_io at {time.strftime('%X')}")
1018           # Note that time.sleep() can be replaced with any blocking
1019           # IO-bound operation, such as file operations.
1020           time.sleep(1)
1021           print(f"blocking_io complete at {time.strftime('%X')}")
1022
1023       async def main():
1024           print(f"started main at {time.strftime('%X')}")
1025
1026           await asyncio.gather(
1027               asyncio.to_thread(blocking_io),
1028               asyncio.sleep(1))
1029
1030           print(f"finished main at {time.strftime('%X')}")
1031
1032
1033       asyncio.run(main())
1034
1035       # Expected output:
1036       #
1037       # started main at 19:50:53
1038       # start blocking_io at 19:50:53
1039       # blocking_io complete at 19:50:54
1040       # finished main at 19:50:54
1041
1042   Directly calling ``blocking_io()`` in any coroutine would block the event loop
1043   for its duration, resulting in an additional 1 second of run time. Instead,
1044   by using ``asyncio.to_thread()``, we can run it in a separate thread without
1045   blocking the event loop.
1046
1047   .. note::
1048
1049      Due to the :term:`GIL`, ``asyncio.to_thread()`` can typically only be used
1050      to make IO-bound functions non-blocking. However, for extension modules
1051      that release the GIL or alternative Python implementations that don't
1052      have one, ``asyncio.to_thread()`` can also be used for CPU-bound functions.
1053
1054   .. versionadded:: 3.9
1055
1056
1057Scheduling From Other Threads
1058=============================
1059
1060.. function:: run_coroutine_threadsafe(coro, loop)
1061
1062   Submit a coroutine to the given event loop.  Thread-safe.
1063
1064   Return a :class:`concurrent.futures.Future` to wait for the result
1065   from another OS thread.
1066
1067   This function is meant to be called from a different OS thread
1068   than the one where the event loop is running.  Example::
1069
1070     # Create a coroutine
1071     coro = asyncio.sleep(1, result=3)
1072
1073     # Submit the coroutine to a given loop
1074     future = asyncio.run_coroutine_threadsafe(coro, loop)
1075
1076     # Wait for the result with an optional timeout argument
1077     assert future.result(timeout) == 3
1078
1079   If an exception is raised in the coroutine, the returned Future
1080   will be notified.  It can also be used to cancel the task in
1081   the event loop::
1082
1083     try:
1084         result = future.result(timeout)
1085     except TimeoutError:
1086         print('The coroutine took too long, cancelling the task...')
1087         future.cancel()
1088     except Exception as exc:
1089         print(f'The coroutine raised an exception: {exc!r}')
1090     else:
1091         print(f'The coroutine returned: {result!r}')
1092
1093   See the :ref:`concurrency and multithreading <asyncio-multithreading>`
1094   section of the documentation.
1095
1096   Unlike other asyncio functions this function requires the *loop*
1097   argument to be passed explicitly.
1098
1099   .. versionadded:: 3.5.1
1100
1101
1102Introspection
1103=============
1104
1105
1106.. function:: current_task(loop=None)
1107
1108   Return the currently running :class:`Task` instance, or ``None`` if
1109   no task is running.
1110
1111   If *loop* is ``None`` :func:`get_running_loop` is used to get
1112   the current loop.
1113
1114   .. versionadded:: 3.7
1115
1116
1117.. function:: all_tasks(loop=None)
1118
1119   Return a set of not yet finished :class:`Task` objects run by
1120   the loop.
1121
1122   If *loop* is ``None``, :func:`get_running_loop` is used for getting
1123   current loop.
1124
1125   .. versionadded:: 3.7
1126
1127
1128.. function:: iscoroutine(obj)
1129
1130   Return ``True`` if *obj* is a coroutine object.
1131
1132   .. versionadded:: 3.4
1133
1134
1135Task Object
1136===========
1137
1138.. class:: Task(coro, *, loop=None, name=None, context=None, eager_start=False)
1139
1140   A :class:`Future-like <Future>` object that runs a Python
1141   :ref:`coroutine <coroutine>`.  Not thread-safe.
1142
1143   Tasks are used to run coroutines in event loops.
1144   If a coroutine awaits on a Future, the Task suspends
1145   the execution of the coroutine and waits for the completion
1146   of the Future.  When the Future is *done*, the execution of
1147   the wrapped coroutine resumes.
1148
1149   Event loops use cooperative scheduling: an event loop runs
1150   one Task at a time.  While a Task awaits for the completion of a
1151   Future, the event loop runs other Tasks, callbacks, or performs
1152   IO operations.
1153
1154   Use the high-level :func:`asyncio.create_task` function to create
1155   Tasks, or the low-level :meth:`loop.create_task` or
1156   :func:`ensure_future` functions.  Manual instantiation of Tasks
1157   is discouraged.
1158
1159   To cancel a running Task use the :meth:`cancel` method.  Calling it
1160   will cause the Task to throw a :exc:`CancelledError` exception into
1161   the wrapped coroutine.  If a coroutine is awaiting on a Future
1162   object during cancellation, the Future object will be cancelled.
1163
1164   :meth:`cancelled` can be used to check if the Task was cancelled.
1165   The method returns ``True`` if the wrapped coroutine did not
1166   suppress the :exc:`CancelledError` exception and was actually
1167   cancelled.
1168
1169   :class:`asyncio.Task` inherits from :class:`Future` all of its
1170   APIs except :meth:`Future.set_result` and
1171   :meth:`Future.set_exception`.
1172
1173   An optional keyword-only *context* argument allows specifying a
1174   custom :class:`contextvars.Context` for the *coro* to run in.
1175   If no *context* is provided, the Task copies the current context
1176   and later runs its coroutine in the copied context.
1177
1178   An optional keyword-only *eager_start* argument allows eagerly starting
1179   the execution of the :class:`asyncio.Task` at task creation time.
1180   If set to ``True`` and the event loop is running, the task will start
1181   executing the coroutine immediately, until the first time the coroutine
1182   blocks. If the coroutine returns or raises without blocking, the task
1183   will be finished eagerly and will skip scheduling to the event loop.
1184
1185   .. versionchanged:: 3.7
1186      Added support for the :mod:`contextvars` module.
1187
1188   .. versionchanged:: 3.8
1189      Added the *name* parameter.
1190
1191   .. deprecated:: 3.10
1192      Deprecation warning is emitted if *loop* is not specified
1193      and there is no running event loop.
1194
1195   .. versionchanged:: 3.11
1196      Added the *context* parameter.
1197
1198   .. versionchanged:: 3.12
1199      Added the *eager_start* parameter.
1200
1201   .. method:: done()
1202
1203      Return ``True`` if the Task is *done*.
1204
1205      A Task is *done* when the wrapped coroutine either returned
1206      a value, raised an exception, or the Task was cancelled.
1207
1208   .. method:: result()
1209
1210      Return the result of the Task.
1211
1212      If the Task is *done*, the result of the wrapped coroutine
1213      is returned (or if the coroutine raised an exception, that
1214      exception is re-raised.)
1215
1216      If the Task has been *cancelled*, this method raises
1217      a :exc:`CancelledError` exception.
1218
1219      If the Task's result isn't yet available, this method raises
1220      an :exc:`InvalidStateError` exception.
1221
1222   .. method:: exception()
1223
1224      Return the exception of the Task.
1225
1226      If the wrapped coroutine raised an exception that exception
1227      is returned.  If the wrapped coroutine returned normally
1228      this method returns ``None``.
1229
1230      If the Task has been *cancelled*, this method raises a
1231      :exc:`CancelledError` exception.
1232
1233      If the Task isn't *done* yet, this method raises an
1234      :exc:`InvalidStateError` exception.
1235
1236   .. method:: add_done_callback(callback, *, context=None)
1237
1238      Add a callback to be run when the Task is *done*.
1239
1240      This method should only be used in low-level callback-based code.
1241
1242      See the documentation of :meth:`Future.add_done_callback`
1243      for more details.
1244
1245   .. method:: remove_done_callback(callback)
1246
1247      Remove *callback* from the callbacks list.
1248
1249      This method should only be used in low-level callback-based code.
1250
1251      See the documentation of :meth:`Future.remove_done_callback`
1252      for more details.
1253
1254   .. method:: get_stack(*, limit=None)
1255
1256      Return the list of stack frames for this Task.
1257
1258      If the wrapped coroutine is not done, this returns the stack
1259      where it is suspended.  If the coroutine has completed
1260      successfully or was cancelled, this returns an empty list.
1261      If the coroutine was terminated by an exception, this returns
1262      the list of traceback frames.
1263
1264      The frames are always ordered from oldest to newest.
1265
1266      Only one stack frame is returned for a suspended coroutine.
1267
1268      The optional *limit* argument sets the maximum number of frames
1269      to return; by default all available frames are returned.
1270      The ordering of the returned list differs depending on whether
1271      a stack or a traceback is returned: the newest frames of a
1272      stack are returned, but the oldest frames of a traceback are
1273      returned.  (This matches the behavior of the traceback module.)
1274
1275   .. method:: print_stack(*, limit=None, file=None)
1276
1277      Print the stack or traceback for this Task.
1278
1279      This produces output similar to that of the traceback module
1280      for the frames retrieved by :meth:`get_stack`.
1281
1282      The *limit* argument is passed to :meth:`get_stack` directly.
1283
1284      The *file* argument is an I/O stream to which the output
1285      is written; by default output is written to :data:`sys.stdout`.
1286
1287   .. method:: get_coro()
1288
1289      Return the coroutine object wrapped by the :class:`Task`.
1290
1291      .. note::
1292
1293         This will return ``None`` for Tasks which have already
1294         completed eagerly. See the :ref:`Eager Task Factory <eager-task-factory>`.
1295
1296      .. versionadded:: 3.8
1297
1298      .. versionchanged:: 3.12
1299
1300         Newly added eager task execution means result may be ``None``.
1301
1302   .. method:: get_context()
1303
1304      Return the :class:`contextvars.Context` object
1305      associated with the task.
1306
1307      .. versionadded:: 3.12
1308
1309   .. method:: get_name()
1310
1311      Return the name of the Task.
1312
1313      If no name has been explicitly assigned to the Task, the default
1314      asyncio Task implementation generates a default name during
1315      instantiation.
1316
1317      .. versionadded:: 3.8
1318
1319   .. method:: set_name(value)
1320
1321      Set the name of the Task.
1322
1323      The *value* argument can be any object, which is then
1324      converted to a string.
1325
1326      In the default Task implementation, the name will be visible
1327      in the :func:`repr` output of a task object.
1328
1329      .. versionadded:: 3.8
1330
1331   .. method:: cancel(msg=None)
1332
1333      Request the Task to be cancelled.
1334
1335      This arranges for a :exc:`CancelledError` exception to be thrown
1336      into the wrapped coroutine on the next cycle of the event loop.
1337
1338      The coroutine then has a chance to clean up or even deny the
1339      request by suppressing the exception with a :keyword:`try` ...
1340      ... ``except CancelledError`` ... :keyword:`finally` block.
1341      Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
1342      not guarantee that the Task will be cancelled, although
1343      suppressing cancellation completely is not common and is actively
1344      discouraged.  Should the coroutine nevertheless decide to suppress
1345      the cancellation, it needs to call :meth:`Task.uncancel` in addition
1346      to catching the exception.
1347
1348      .. versionchanged:: 3.9
1349         Added the *msg* parameter.
1350
1351      .. versionchanged:: 3.11
1352         The ``msg`` parameter is propagated from cancelled task to its awaiter.
1353
1354      .. _asyncio_example_task_cancel:
1355
1356      The following example illustrates how coroutines can intercept
1357      the cancellation request::
1358
1359          async def cancel_me():
1360              print('cancel_me(): before sleep')
1361
1362              try:
1363                  # Wait for 1 hour
1364                  await asyncio.sleep(3600)
1365              except asyncio.CancelledError:
1366                  print('cancel_me(): cancel sleep')
1367                  raise
1368              finally:
1369                  print('cancel_me(): after sleep')
1370
1371          async def main():
1372              # Create a "cancel_me" Task
1373              task = asyncio.create_task(cancel_me())
1374
1375              # Wait for 1 second
1376              await asyncio.sleep(1)
1377
1378              task.cancel()
1379              try:
1380                  await task
1381              except asyncio.CancelledError:
1382                  print("main(): cancel_me is cancelled now")
1383
1384          asyncio.run(main())
1385
1386          # Expected output:
1387          #
1388          #     cancel_me(): before sleep
1389          #     cancel_me(): cancel sleep
1390          #     cancel_me(): after sleep
1391          #     main(): cancel_me is cancelled now
1392
1393   .. method:: cancelled()
1394
1395      Return ``True`` if the Task is *cancelled*.
1396
1397      The Task is *cancelled* when the cancellation was requested with
1398      :meth:`cancel` and the wrapped coroutine propagated the
1399      :exc:`CancelledError` exception thrown into it.
1400
1401   .. method:: uncancel()
1402
1403      Decrement the count of cancellation requests to this Task.
1404
1405      Returns the remaining number of cancellation requests.
1406
1407      Note that once execution of a cancelled task completed, further
1408      calls to :meth:`uncancel` are ineffective.
1409
1410      .. versionadded:: 3.11
1411
1412      This method is used by asyncio's internals and isn't expected to be
1413      used by end-user code.  In particular, if a Task gets successfully
1414      uncancelled, this allows for elements of structured concurrency like
1415      :ref:`taskgroups` and :func:`asyncio.timeout` to continue running,
1416      isolating cancellation to the respective structured block.
1417      For example::
1418
1419        async def make_request_with_timeout():
1420            try:
1421                async with asyncio.timeout(1):
1422                    # Structured block affected by the timeout:
1423                    await make_request()
1424                    await make_another_request()
1425            except TimeoutError:
1426                log("There was a timeout")
1427            # Outer code not affected by the timeout:
1428            await unrelated_code()
1429
1430      While the block with ``make_request()`` and ``make_another_request()``
1431      might get cancelled due to the timeout, ``unrelated_code()`` should
1432      continue running even in case of the timeout.  This is implemented
1433      with :meth:`uncancel`.  :class:`TaskGroup` context managers use
1434      :func:`uncancel` in a similar fashion.
1435
1436      If end-user code is, for some reason, suppressing cancellation by
1437      catching :exc:`CancelledError`, it needs to call this method to remove
1438      the cancellation state.
1439
1440      When this method decrements the cancellation count to zero,
1441      the method checks if a previous :meth:`cancel` call had arranged
1442      for :exc:`CancelledError` to be thrown into the task.
1443      If it hasn't been thrown yet, that arrangement will be
1444      rescinded (by resetting the internal ``_must_cancel`` flag).
1445
1446   .. versionchanged:: 3.13
1447      Changed to rescind pending cancellation requests upon reaching zero.
1448
1449   .. method:: cancelling()
1450
1451      Return the number of pending cancellation requests to this Task, i.e.,
1452      the number of calls to :meth:`cancel` less the number of
1453      :meth:`uncancel` calls.
1454
1455      Note that if this number is greater than zero but the Task is
1456      still executing, :meth:`cancelled` will still return ``False``.
1457      This is because this number can be lowered by calling :meth:`uncancel`,
1458      which can lead to the task not being cancelled after all if the
1459      cancellation requests go down to zero.
1460
1461      This method is used by asyncio's internals and isn't expected to be
1462      used by end-user code.  See :meth:`uncancel` for more details.
1463
1464      .. versionadded:: 3.11
1465