Trio Typing
trio-typing provides static type checking support for Trio and related projects. It offers PEP 561 typing stubs for `trio`, `outcome`, and `async_generator`, along with a `mypy` plugin to enhance type checking capabilities for asynchronous code. The current version is 0.10.0, and it follows the release cadence of the broader Trio ecosystem.
Warnings
- breaking Versions of trio-typing 0.10.0 and later require Mypy 1.0 or newer due to changes in Mypy's plugin API.
- deprecated The `Nursery` type should now be imported directly from the `trio` package (`from trio import Nursery`). Importing `Nursery` from `trio_typing` is deprecated.
- gotcha While Trio itself supports both CPython and PyPy runtimes, static type checking with `mypy` and `trio-typing` must currently occur on CPython environments, due to limitations of `mypy`.
- gotcha When listing dependencies for a library that uses `trio_typing`, avoid specifying `trio-typing[mypy]` in `install_requires`. This would needlessly add a `mypy` dependency to every application transitively depending on your library. Instead, list `trio-typing` as a regular dependency and specify `mypy` (and `trio-typing[mypy]`) in development-specific dependencies (e.g., `requirements-dev.txt` or `pyproject.toml`'s `[project.optional-dependencies.dev]`).
Install
-
pip install trio-typing -
pip install trio-typing[mypy]
Imports
- TaskStatus
from trio_typing import TaskStatus
- AsyncGenerator
from trio_typing import AsyncGenerator
- Nursery
from trio import Nursery
- plugin
plugins = trio_typing.plugin # in mypy.ini
Quickstart
import trio
from trio_typing import TaskStatus
from typing import TypeVar
T = TypeVar("T")
async def child_task(value: T, *, task_status: TaskStatus[T]) -> None:
"""An asynchronous task that signals its start status."""
print(f"Child task received: {value}")
task_status.started(f"Processed: {value}") # Type-checked by trio-typing
await trio.sleep(0.1)
async def main() -> None:
"""Main function demonstrating nursery.start with type hints."""
print("Starting main...")
async with trio.open_nursery() as nursery:
# mypy will check that 'child_task' matches the expected signature for nursery.start
result = await nursery.start(child_task, "hello")
print(f"Nursery start returned: {result}")
print("Main finished.")
if __name__ == "__main__":
# To enable mypy checks, ensure you have mypy installed with trio-typing[mypy]
# and 'plugins = trio_typing.plugin' in your mypy.ini file.
# Example mypy.ini:
# [mypy]
# plugins = trio_typing.plugin
#
# Then run: mypy your_script_name.py
trio.run(main)