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, timeout)
| 438 | |
| 439 | |
| 440 | async def wait_for(fut, timeout): |
| 441 | """Wait for the single Future or coroutine to complete, with timeout. |
| 442 | |
| 443 | Coroutine will be wrapped in Task. |
| 444 | |
| 445 | Returns result of the Future or coroutine. When a timeout occurs, |
| 446 | it cancels the task and raises TimeoutError. To avoid the task |
| 447 | cancellation, wrap it in shield(). |
| 448 | |
| 449 | If the wait is cancelled, the task is also cancelled. |
| 450 | |
| 451 | If the task suppresses the cancellation and returns a value instead, |
| 452 | that value is returned. |
| 453 | |
| 454 | This function is a coroutine. |
| 455 | """ |
| 456 | # The special case for timeout <= 0 is for the following case: |
| 457 | # |
| 458 | # async def test_waitfor(): |
| 459 | # func_started = False |
| 460 | # |
| 461 | # async def func(): |
| 462 | # nonlocal func_started |
| 463 | # func_started = True |
| 464 | # |
| 465 | # try: |
| 466 | # await asyncio.wait_for(func(), 0) |
| 467 | # except asyncio.TimeoutError: |
| 468 | # assert not func_started |
| 469 | # else: |
| 470 | # assert False |
| 471 | # |
| 472 | # asyncio.run(test_waitfor()) |
| 473 | |
| 474 | |
| 475 | if timeout is not None and timeout <= 0: |
| 476 | fut = ensure_future(fut) |
| 477 | |
| 478 | if fut.done(): |
| 479 | return fut.result() |
| 480 | |
| 481 | await _cancel_and_wait(fut) |
| 482 | try: |
| 483 | return fut.result() |
| 484 | except exceptions.CancelledError as exc: |
| 485 | raise TimeoutError from exc |
| 486 | |
| 487 | async with timeouts.timeout(timeout): |
| 488 | return await fut |
| 489 | |
| 490 | async def _wait(fs, timeout, return_when, loop): |
| 491 | """Internal helper for wait(). |
searching dependent graphs…