From f2a3319d8e9d96e51b79aa57fc9fc9aa6605824e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Sat, 9 Jul 2022 18:37:26 +0200 Subject: [PATCH 01/10] bpo46771 docs --- Doc/library/asyncio-task.rst | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 76969762dd9f55..57844073f1909c 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -282,6 +282,23 @@ Creating Tasks Added the *context* parameter. +Task Cancellation +================= + +Tasks can easily and safely be cancelled. +When a task is cancelled, asyncio will raise a :exc:`asyncio.CancelledError` +into the task at the next opportunity. + +Coroutines should only catch :exc:`asyncio.CancelledError` if they +need to perform clean-up logic when they are cancelled, and even in +that case the :exc:`asyncio.CancelledError` should be propagated when +clean-up is complete. Most code can safely ignore `CancelledError`. + +Important asyncio components, like :class:`asyncio.TaskGroup` and the +:func:`asyncio.timeout` context manager, are implemented using cancellation +internally. + + Task Groups =========== @@ -537,6 +554,56 @@ Shielding From Cancellation Timeouts ======== +A convenient way to limit the amount of time spent waiting on +something is to use the :func:`asyncio.timeout` and +:func:`asyncio.timeout_at` +:ref:`asynchronous context manager `. + +Example:: + + async def main(): + async with asyncio.timeout(10): + await long_running_task() + +If ``long_running_task`` takes more than 10 seconds to complete, +the context manager will cancel the current task and handle +the resulting :exc:`asyncio.CancelledError` internally, transforming it +into a :exc:`asyncio.TimeoutError`, which can be caught and handled. + +Example:: + + async def main(): + try: + async with asyncio.timeout_at(deadline): + await long_running_task() + except TimeoutError: + print("The long operation timed out, but we've handled it.") + + print("This statement will run regardless.") + +The context manager produced by :func:`asyncio.timeout` can be +rescheduled to a different deadline and inspected. + +Example:: + + async def main(): + try: + async with asyncio.timeout(10) as cm: + # We changed our mind, giving it more time. + new_deadline = cm.when + 10 + cm.reschedule(new_deadline) + + await long_running_task() + except TimeoutError: + pass + + if cm.expired: + print("Looks like we haven't finished on time.") + +The timeout context managers can be safely nested. + +.. versionadded:: 3.7 + .. coroutinefunction:: wait_for(aw, timeout) Wait for the *aw* :ref:`awaitable ` From 4ab4f6cab5c45a3c49c51cf06bf194b3c5433528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Sun, 10 Jul 2022 19:41:21 +0200 Subject: [PATCH 02/10] Flesh out timeout_at docs --- Doc/library/asyncio-task.rst | 100 ++++++++++++++++++++++------------- 1 file changed, 64 insertions(+), 36 deletions(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 57844073f1909c..56aa10174b4504 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -554,55 +554,83 @@ Shielding From Cancellation Timeouts ======== -A convenient way to limit the amount of time spent waiting on -something is to use the :func:`asyncio.timeout` and -:func:`asyncio.timeout_at` -:ref:`asynchronous context manager `. +.. coroutinefunction:: timeout(delay) -Example:: + A convenient way to limit the amount of time spent waiting on + something is to use the :func:`asyncio.timeout` and + :func:`asyncio.timeout_at` + :ref:`asynchronous context manager `. - async def main(): - async with asyncio.timeout(10): - await long_running_task() + *delay* can either be ``None`` or a float or int number of + seconds to wait. If *delay* is ``None``, no time limit will + be applied. In either case, the context manager can be + rescheduled after creation. -If ``long_running_task`` takes more than 10 seconds to complete, -the context manager will cancel the current task and handle -the resulting :exc:`asyncio.CancelledError` internally, transforming it -into a :exc:`asyncio.TimeoutError`, which can be caught and handled. + Example:: -Example:: - - async def main(): - try: - async with asyncio.timeout_at(deadline): + async def main(): + async with asyncio.timeout(10): await long_running_task() - except TimeoutError: - print("The long operation timed out, but we've handled it.") - print("This statement will run regardless.") + If ``long_running_task`` takes more than 10 seconds to complete, + the context manager will cancel the current task and handle + the resulting :exc:`asyncio.CancelledError` internally, transforming it + into a :exc:`asyncio.TimeoutError` which can be caught and handled. -The context manager produced by :func:`asyncio.timeout` can be -rescheduled to a different deadline and inspected. + Example:: -Example:: + async def main(): + try: + async with asyncio.timeout(10): + await long_running_task() + except TimeoutError: + print("The long operation timed out, but we've handled it.") - async def main(): - try: - async with asyncio.timeout(10) as cm: - # We changed our mind, giving it more time. - new_deadline = cm.when + 10 - cm.reschedule(new_deadline) + print("This statement will run regardless.") - await long_running_task() - except TimeoutError: - pass + The context manager produced by :func:`asyncio.timeout` can be + rescheduled to a different deadline and inspected. + + Example:: + + async def main(): + try: + # We do not know the timeout when starting, so we pass ``None``. + async with asyncio.timeout(None) as cm: + # We know the timeout now, so we reschedule it. + new_deadline = get_running_loop().time() + 10 + cm.reschedule(new_deadline) - if cm.expired: - print("Looks like we haven't finished on time.") + await long_running_task() + except TimeoutError: + pass -The timeout context managers can be safely nested. + if cm.expired: + print("Looks like we haven't finished on time.") -.. versionadded:: 3.7 + The timeout context managers can be safely nested. + + .. versionadded:: 3.11 + +.. coroutinefunction:: timeout_at(when) + + Similar to :ref:`asyncio.timeout`, except *when* is the absolute time + to stop waiting, or ``None``. + + Example:: + + async def main(): + loop = get_running_loop() + deadline = loop.time() + 20 + try: + async with asyncio.timeout_at(deadline): + await long_running_task() + except TimeoutError: + print("The long operation timed out, but we've handled it.") + + print("This statement will run regardless.") + + .. versionadded:: 3.11 .. coroutinefunction:: wait_for(aw, timeout) From 0592fce6f2d341f8aabb4cb906de243c5fb7aafa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Sun, 10 Jul 2022 23:59:08 +0200 Subject: [PATCH 03/10] Tweak reference --- Doc/library/asyncio-task.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 56aa10174b4504..e1847ddc7c9fc1 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -614,7 +614,7 @@ Timeouts .. coroutinefunction:: timeout_at(when) - Similar to :ref:`asyncio.timeout`, except *when* is the absolute time + Similar to :func:`asyncio.timeout`, except *when* is the absolute time to stop waiting, or ``None``. Example:: From dd3bf3d6debfebd5d301ff8370063135c910d5a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Tue, 12 Jul 2022 01:28:49 +0200 Subject: [PATCH 04/10] Documentation tweaks as per review --- Doc/library/asyncio-task.rst | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index e1847ddc7c9fc1..2f22bad22e1135 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -289,10 +289,10 @@ Tasks can easily and safely be cancelled. When a task is cancelled, asyncio will raise a :exc:`asyncio.CancelledError` into the task at the next opportunity. -Coroutines should only catch :exc:`asyncio.CancelledError` if they -need to perform clean-up logic when they are cancelled, and even in -that case the :exc:`asyncio.CancelledError` should be propagated when -clean-up is complete. Most code can safely ignore `CancelledError`. +Coroutines are recommended to use ``try/finally`` blocks to robustly +perform clean-up logic. In the case the :exc:`asyncio.CancelledError` +is explicitly caught, it should generally be propagated when +clean-up is complete. Most code can safely ignore :exc:`asyncio.CancelledError`. Important asyncio components, like :class:`asyncio.TaskGroup` and the :func:`asyncio.timeout` context manager, are implemented using cancellation @@ -557,8 +557,7 @@ Timeouts .. coroutinefunction:: timeout(delay) A convenient way to limit the amount of time spent waiting on - something is to use the :func:`asyncio.timeout` and - :func:`asyncio.timeout_at` + something is to use the :func:`asyncio.timeout` :ref:`asynchronous context manager `. *delay* can either be ``None`` or a float or int number of @@ -577,7 +576,14 @@ Timeouts the resulting :exc:`asyncio.CancelledError` internally, transforming it into a :exc:`asyncio.TimeoutError` which can be caught and handled. - Example:: + .. note:: + + The :func:`asyncio.timeout` context manager is what transforms + the :exc:`asyncio.CancelledError` into an :exc:`asyncio.TimeoutError`, + which means the :exc:`asyncio.TimeoutError` can only be caught + *outside* of the context manager. + + Example of catching :exc:`asyncio.TimeoutError`:: async def main(): try: @@ -608,7 +614,7 @@ Timeouts if cm.expired: print("Looks like we haven't finished on time.") - The timeout context managers can be safely nested. + Timeout context managers can be safely nested. .. versionadded:: 3.11 From ab14b9ee0e206884ee09f98f01923e3987ef46d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Wed, 13 Jul 2022 00:58:01 +0200 Subject: [PATCH 05/10] Doc feedback --- Doc/library/asyncio-task.rst | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 2f22bad22e1135..8e72493fe502a9 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -289,14 +289,15 @@ Tasks can easily and safely be cancelled. When a task is cancelled, asyncio will raise a :exc:`asyncio.CancelledError` into the task at the next opportunity. -Coroutines are recommended to use ``try/finally`` blocks to robustly +It is recommended that coroutines use ``try/finally`` blocks to robustly perform clean-up logic. In the case the :exc:`asyncio.CancelledError` is explicitly caught, it should generally be propagated when clean-up is complete. Most code can safely ignore :exc:`asyncio.CancelledError`. Important asyncio components, like :class:`asyncio.TaskGroup` and the :func:`asyncio.timeout` context manager, are implemented using cancellation -internally. +internally and might misbehave if a coroutine swallows +:exc:`asyncio.CancelledError`. Task Groups @@ -560,10 +561,13 @@ Timeouts something is to use the :func:`asyncio.timeout` :ref:`asynchronous context manager `. - *delay* can either be ``None`` or a float or int number of + *delay* can either be ``None``, or a float/int number of seconds to wait. If *delay* is ``None``, no time limit will - be applied. In either case, the context manager can be - rescheduled after creation. + be applied; this can be useful if the delay is unknown when + the context manager is created. + + In either case, the context manager can be rescheduled after + creation using :meth:`asyncio.Timeout.reschedule`. Example:: @@ -574,7 +578,7 @@ Timeouts If ``long_running_task`` takes more than 10 seconds to complete, the context manager will cancel the current task and handle the resulting :exc:`asyncio.CancelledError` internally, transforming it - into a :exc:`asyncio.TimeoutError` which can be caught and handled. + into an :exc:`asyncio.TimeoutError` which can be caught and handled. .. note:: From a30b814078481df7f2de3a65e0f466384a24231b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Thu, 14 Jul 2022 01:03:14 +0200 Subject: [PATCH 06/10] Update Doc/library/asyncio-task.rst Co-authored-by: Guido van Rossum --- Doc/library/asyncio-task.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 8e72493fe502a9..57f2b36eb0b977 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -290,7 +290,7 @@ When a task is cancelled, asyncio will raise a :exc:`asyncio.CancelledError` into the task at the next opportunity. It is recommended that coroutines use ``try/finally`` blocks to robustly -perform clean-up logic. In the case the :exc:`asyncio.CancelledError` +perform clean-up logic. In case :exc:`asyncio.CancelledError` is explicitly caught, it should generally be propagated when clean-up is complete. Most code can safely ignore :exc:`asyncio.CancelledError`. From 476454fea157ddb61f1d3d97962ba8520d2767cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Thu, 14 Jul 2022 01:08:25 +0200 Subject: [PATCH 07/10] Review tweaks --- Doc/library/asyncio-task.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 57f2b36eb0b977..c3dab03c86ca3a 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -286,8 +286,8 @@ Task Cancellation ================= Tasks can easily and safely be cancelled. -When a task is cancelled, asyncio will raise a :exc:`asyncio.CancelledError` -into the task at the next opportunity. +When a task is cancelled, asyncio will raise :exc:`asyncio.CancelledError` +in the task at the next opportunity. It is recommended that coroutines use ``try/finally`` blocks to robustly perform clean-up logic. In case :exc:`asyncio.CancelledError` @@ -557,9 +557,9 @@ Timeouts .. coroutinefunction:: timeout(delay) - A convenient way to limit the amount of time spent waiting on - something is to use the :func:`asyncio.timeout` - :ref:`asynchronous context manager `. + An :ref:`asynchronous context manager ` + that can be used to limit the amount of time spent waiting on + something. *delay* can either be ``None``, or a float/int number of seconds to wait. If *delay* is ``None``, no time limit will From 6e066debda2b5c8848f900e1009796a6f49c32dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Thu, 14 Jul 2022 01:40:07 +0200 Subject: [PATCH 08/10] More docs --- Doc/library/asyncio-task.rst | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index c3dab03c86ca3a..d4adc263e4ada8 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -567,7 +567,7 @@ Timeouts the context manager is created. In either case, the context manager can be rescheduled after - creation using :meth:`asyncio.Timeout.reschedule`. + creation using :meth:`Timeout.reschedule`. Example:: @@ -601,6 +601,35 @@ Timeouts The context manager produced by :func:`asyncio.timeout` can be rescheduled to a different deadline and inspected. + .. class:: Timeout() + + An :ref:`asynchronous context manager ` + that limits time spent inside of it. + + .. versionadded:: 3.11 + + .. method:: when() -> float | None + + Return the current deadline, or `None` if the current + deadline is not set. + + The deadline is a float, consistent with the time returned by + :meth:`loop.time`. + + .. method:: reschedule(when: float | None) + + Change the time the timeout will trigger. + + If *when* is `None`, any current deadline will be removed, and the + context manager will wait indefinitely. + + If *when* is a float, it is set as the new deadline. + + .. method:: expired() -> bool + + Return whether the context manager has exceeded its deadline + (expired). + Example:: async def main(): From 3069a5cdb61ad96b973976b912742948952cf94d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Thu, 14 Jul 2022 01:42:43 +0200 Subject: [PATCH 09/10] Reword --- Doc/library/asyncio-task.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index d4adc263e4ada8..4b5c0bed0bb57f 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -286,7 +286,7 @@ Task Cancellation ================= Tasks can easily and safely be cancelled. -When a task is cancelled, asyncio will raise :exc:`asyncio.CancelledError` +When a task is cancelled, :exc:`asyncio.CancelledError` will be raised in the task at the next opportunity. It is recommended that coroutines use ``try/finally`` blocks to robustly From 9fe990a1118f7d2c3ac9608b04e64f9e522a2d32 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Thu, 14 Jul 2022 19:32:16 -0700 Subject: [PATCH 10/10] Fix markup --- Doc/library/asyncio-task.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 4b5c0bed0bb57f..a307d22e456ebf 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -610,7 +610,7 @@ Timeouts .. method:: when() -> float | None - Return the current deadline, or `None` if the current + Return the current deadline, or ``None`` if the current deadline is not set. The deadline is a float, consistent with the time returned by