From 4c6a60a98f80cac19a02f7b81a68007f749d754c Mon Sep 17 00:00:00 2001 From: twisteroid ambassador Date: Wed, 19 Oct 2022 12:37:58 +0800 Subject: [PATCH] Refactor `wait_for` with `wait`. --- Lib/asyncio/tasks.py | 66 +++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 38 deletions(-) diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 571013745aa03a..e9fca5278ac080 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -444,9 +444,9 @@ async def wait_for(fut, timeout): if timeout is None: return await fut - if timeout <= 0: - fut = ensure_future(fut, loop=loop) + fut = ensure_future(fut, loop=loop) + if timeout <= 0: if fut.done(): return fut.result() @@ -456,45 +456,35 @@ async def wait_for(fut, timeout): except exceptions.CancelledError as exc: raise exceptions.TimeoutError() from exc - waiter = loop.create_future() - timeout_handle = loop.call_later(timeout, _release_waiter, waiter) - cb = functools.partial(_release_waiter, waiter) + try: + await wait((fut,), timeout=timeout) + except exceptions.CancelledError: + # wait_for() is being cancelled from the outside. - fut = ensure_future(fut, loop=loop) - fut.add_done_callback(cb) + # We must ensure that the task is not running + # after wait_for() returns. + # See https://bugs.python.org/issue32751 + await _cancel_and_wait(fut, loop=loop) + raise - try: - # wait until the future completes or the timeout - try: - await waiter - except exceptions.CancelledError: - if fut.done(): - return fut.result() - else: - fut.remove_done_callback(cb) - # We must ensure that the task is not running - # after wait_for() returns. - # See https://bugs.python.org/issue32751 - await _cancel_and_wait(fut, loop=loop) - raise + # either fut is done, or timeout exceeded, or both + if fut.done(): + return fut.result() + # If fut was cancelled by something else, this will also propagate its CancelledError. - if fut.done(): - return fut.result() - else: - fut.remove_done_callback(cb) - # We must ensure that the task is not running - # after wait_for() returns. - # See https://bugs.python.org/issue32751 - await _cancel_and_wait(fut, loop=loop) - # In case task cancellation failed with some - # exception, we should re-raise it - # See https://bugs.python.org/issue40607 - try: - return fut.result() - except exceptions.CancelledError as exc: - raise exceptions.TimeoutError() from exc - finally: - timeout_handle.cancel() + # timeout was exceeded + + # We must ensure that the task is not running + # after wait_for() returns. + # See https://bugs.python.org/issue32751 + await _cancel_and_wait(fut, loop=loop) + # In case task cancellation failed with some + # exception, we should re-raise it + # See https://bugs.python.org/issue40607 + try: + return fut.result() + except exceptions.CancelledError as exc: + raise exceptions.TimeoutError() from exc async def _wait(fs, timeout, return_when, loop):