Debian Codegraph @

Doc/library/asyncio-task.rst

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