Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 28 additions & 38 deletions Lib/asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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):
Expand Down