Wait for the single Future or coroutine to complete, with timeout. Coroutine will be wrapped in Task. Returns result of the Future or coroutine. When a timeout occurs, it cancels the task and raises TimeoutError. To avoid the task cancellation, wrap it in shield(). If the wa
(fut: compat.Awaitable[_T], timeout: float | None)
| 23 | |
| 24 | |
| 25 | async def wait_for(fut: compat.Awaitable[_T], timeout: float | None) -> _T: |
| 26 | """Wait for the single Future or coroutine to complete, with timeout. |
| 27 | |
| 28 | Coroutine will be wrapped in Task. |
| 29 | |
| 30 | Returns result of the Future or coroutine. When a timeout occurs, |
| 31 | it cancels the task and raises TimeoutError. To avoid the task |
| 32 | cancellation, wrap it in shield(). |
| 33 | |
| 34 | If the wait is cancelled, the task is also cancelled. |
| 35 | |
| 36 | If the task suppresses the cancellation and returns a value instead, |
| 37 | that value is returned. |
| 38 | |
| 39 | This function is a coroutine. |
| 40 | """ |
| 41 | # The special case for timeout <= 0 is for the following case: |
| 42 | # |
| 43 | # async def test_waitfor(): |
| 44 | # func_started = False |
| 45 | # |
| 46 | # async def func(): |
| 47 | # nonlocal func_started |
| 48 | # func_started = True |
| 49 | # |
| 50 | # try: |
| 51 | # await asyncio.wait_for(func(), 0) |
| 52 | # except asyncio.TimeoutError: |
| 53 | # assert not func_started |
| 54 | # else: |
| 55 | # assert False |
| 56 | # |
| 57 | # asyncio.run(test_waitfor()) |
| 58 | |
| 59 | if timeout is not None and timeout <= 0: |
| 60 | fut = asyncio.ensure_future(fut) |
| 61 | |
| 62 | if fut.done(): |
| 63 | return fut.result() |
| 64 | |
| 65 | await _cancel_and_wait(fut) |
| 66 | try: |
| 67 | return fut.result() |
| 68 | except asyncio.CancelledError as exc: |
| 69 | raise TimeoutError from exc |
| 70 | |
| 71 | async with timeout_ctx(timeout): |
| 72 | return await fut |
| 73 | |
| 74 | |
| 75 | async def _cancel_and_wait(fut: asyncio.Future[_T]) -> None: |
nothing calls this directly
no test coverage detected