CKTIS / Python
asyncio.wait_for
Espera una operación con límite en segundos o indefinidamente con None.
Versión: Python 3.14; repository image, production runtime not attested
Sintaxis
await asyncio.wait_for(aw, timeout)Espera una operación con límite en segundos o indefinidamente con None.
Al vencer solicita cancelación y espera su tratamiento, por lo que la limpieza puede superar el límite. La cancelación propagada produce TimeoutError, pero si se captura y se devuelve un valor puede recibirse ese valor.
Aquí cero cancela la tarea y la segunda llamada devuelve 9.
import asyncio
async def main():
start = asyncio.Event()
async def recover():
start.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
return 7
t = asyncio.create_task(recover())
await start.wait()
assert await asyncio.wait_for(t, 0) == 7
assert await asyncio.wait_for(asyncio.sleep(0, result=9), None) == 9
asyncio.run(main())
Ejemplos
import asyncio
async def main():
task = asyncio.create_task(asyncio.Event().wait())
try:
await asyncio.wait_for(task, timeout=0)
except TimeoutError:
print(task.cancelled())
print(await asyncio.wait_for(asyncio.sleep(0, result=9), timeout=5))
asyncio.run(main())
Resultado
True 9
Aquí cero cancela la tarea y la segunda llamada devuelve 9.