Backports Asyncio Runner
Backport of Python 3.11's `asyncio.Runner`, a context manager that simplifies managing the asyncio event loop lifecycle for Python versions 3.8, 3.9, and 3.10. It provides full compatibility with Python 3.11 `asyncio.Runner` features, including contextvars support. Version 1.2.0 is current, with recent releases indicating an active maintenance cadence.
Warnings
- breaking This backport is intended *only* for Python versions 3.8, 3.9, and 3.10. Users of Python 3.11 or above should use the native `asyncio.Runner` from the standard library directly and should *not* install this package.
- gotcha The backport uses `asyncio.tasks._PyTask` instead of `asyncio.tasks._CTask` internally to support `asyncio.Runner` requirements. This can lead to unexpected behavior or `False` results when checking `isinstance(some_task, asyncio.Task)` or `isinstance(some_future, asyncio.Future)`, as `asyncio.Task` might default to `_CTask` elsewhere.
- gotcha There is a slight performance degradation when using this backported `asyncio.Runner` implementation compared to the native Python 3.11 or above version. This is due to the lack of a `_CTask` backport.
- gotcha It's recommended to include a Python version marker (e.g., `python_version < '3.11'`) in your installation commands or `install_requires` to prevent accidental installation of this backport on Python 3.11 or later environments.
Install
-
pip install backports-asyncio-runner -
pip install 'backports-asyncio-runner; python_version < "3.11"'
Imports
- Runner
from backports.asyncio.runner import Runner
Quickstart
import sys
if sys.version_info < (3, 11):
from backports.asyncio.runner import Runner
else:
from asyncio import Runner
async def echo(msg: str) -> None:
print(f"Hello {msg}")
with Runner() as runner:
runner.run(echo("World"))
# To use with uvloop (if installed):
# import uvloop
# with Runner(loop_factory=uvloop.new_event_loop) as runner:
# runner.run(echo("UVLoop World"))