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