Python Glossary Русский

Python 3.11+Async programmingterm

asyncio.Runner

event loop

A context manager that keeps one event loop alive across several run() calls. It is asyncio.run() whose loop is not closed between calls.

Syntax

with asyncio.Runner(*, debug=None, loop_factory=None) as runner: runner.run(coro)

asyncio.run() creates and closes a fresh loop every time, so loop-bound objects (a connection, an asyncio.Lock someone waited on) break with RuntimeError on the second call. Runner fixes that: inside one with block you can call runner.run(a()) and runner.run(b()) on a shared loop — handy in tests and in synchronous code that calls async code piece by piece. You cannot call runner.run() inside a running loop; use await there.

Examples

import asyncio
async def step(n):
    await asyncio.sleep(0.01)
    return id(asyncio.get_running_loop())
with asyncio.Runner() as runner:
    first = runner.run(step(1))
    second = runner.run(step(2))
    print(first == second)  # → True — цикл один и тот же
import asyncio
with asyncio.Runner() as runner:
    runner.run(asyncio.sleep(0.01))
    loop = runner.get_loop()
    print(loop.is_closed())  # → False
print(loop.is_closed())  # → True — выход из with закрыл цикл

See also

Open in the full glossarydocs.python.orgReport an inaccuracy