Type stub generation (*.pyi files) and introspection
This feature is still in active development. See the related issue.
For documentation on type stubs and how to use them with stable PyO3, refer to this page
PyO3 has a work in progress support to generate type stub files.
It works using:
- PyO3 macros (
#[pyclass]) that generate constant JSON strings that are then included in the built binaries by rustc if theexperimental-inspectfeature is enabled. - The
pyo3-introspectioncrate that can parse the generated binaries, extract the JSON strings and build stub files from it. - Build tools like
maturinexposing options in their CLI API to generate the stubs file.
For example, the following Rust code
#[pymodule]
pub mod example {
use pyo3::prelude::*;
#[pymodule_export]
pub const CONSTANT: &str = "FOO";
#[pyclass(eq)]
#[derive(Eq)]
struct Class {
value: usize
}
#[pymethods]
impl Class {
#[new]
fn new(value: usize) -> Self {
Self { value }
}
#[getter]
fn value(&self) -> usize {
self.value
}
}
#[pyfunction]
#[pyo3(signature = (arg: "list[int]") -> "list[int]")]
fn list_of_int_identity(arg: Bound<'_, PyAny>) -> Bound<'_, PyAny> {
arg
}
}
will generate the following stub file:
import typing
__all__ = ["CONSTANT", "Class", "list_of_int_identity"]
CONSTANT: typing.Final = "FOO"
class Class:
def __init__(self, value: typing.SupportsIndex) -> None: ...
@property
def value(self) -> int: ...
def __eq__(self, value: object, /) -> bool: ...
def __ne__(self, value: object, /) -> bool: ...
def list_of_int_identity(arg: "list[int]") -> "list[int]": ...
The only piece of new syntax is that the #[pyo3(signature = ...)] attribute can contain type annotations like #[pyo3(signature = (arg: "list[int]") -> "list[int]")] (note the "" around type annotations).
This is useful when PyO3 is not able to derive proper type annotations by itself.
To generate stubs file with maturin you can use maturin generate-stubs --output stubs that will build the project then generate the stubs in the stubs directory.
You can also directly integrate the stubs in the built wheels by doing maturin build --generate-stubs (works also with maturin develop).
PyO3 also provides the smaller pyo3-introspection binary that allows to generate stubs from an existing built extension using something like pyo3-introspection my_module_binary.so my_module_name output to introspect the my_module_binary.so dynamic library for the my_module_name Python module and generate its stubs in the output directory.
Protocols
pyprotocol! declares a typing.Protocol that only exists in the generated stubs.
It is meant for Rust types that implement FromPyObject and accept any object providing a set of methods: their FromPyObject::INPUT_TYPE can then be the protocol instead of a concrete class.
Like FromPyObject::INPUT_TYPE, it is only available with the experimental-inspect feature.
It also works in library crates:
pyo3::pyprotocol! {
/// A binary stream that can be read from and written to
pub SupportsReadWrite {
#[pyo3(signature = (n = -1, /))]
fn read(&self, n: isize) -> Py<PyBytes>;
fn write(&self, data: &[u8]) -> usize;
}
}
impl<'py> FromPyObject<'_, 'py> for ReadWriteFile<'py> {
const INPUT_TYPE: PyStaticExpr = SupportsReadWrite::TYPE_HINT;
// ...
}
A #[pyfunction] taking a ReadWriteFile is then annotated with the protocol, which is private by default:
@type_check_only
class _SupportsReadWrite(Protocol):
"""
A binary stream that can be read from and written to
"""
def read(self, n: int = ..., /) -> bytes: ...
def write(self, data: bytes, /) -> SupportsIndex: ...
def write_to(f: _SupportsReadWrite, data: bytes) -> int: ...
- The methods describe calls made from Rust, so argument types use
IntoPyObject::OUTPUT_TYPEand return typesFromPyObject::INPUT_TYPE. Parameters are positional-only unless a#[pyo3(signature = (...))]is given, so that implementations can name them freely. - A private protocol only appears in the stubs if a type hint refers to it. It is declared in the deepest module containing all the modules that use it, so its module may change when it is used elsewhere.
- It only exists in the stubs, hence
@type_check_onlyand it is not listed in__all__. - Its name must not clash with another member of the module it is declared in, otherwise stub generation fails;
#[pyo3(name = "...")]sets another name. - Protocols can only declare methods: attributes, properties and generic protocols are not supported yet.
Public protocols
To let Python code refer to a protocol, export it from a module with #[pymodule_export], like a class.
It is then declared in that module under its own name, even if no type hint refers to it:
#[pymodule]
mod my_module {
#[pymodule_export]
use super::SupportsReadWrite;
}
Since it only exists in the stubs, it can be imported in an if TYPE_CHECKING: block, but not at runtime:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from my_module import SupportsReadWrite
The module exporting a protocol decides where it is public, so this also works for protocols declared in library crates, e.g. use some_library::SupportsRead;.
A library can also gather its protocols in a #[pymodule] that exports them, so that an extension module makes them all public with a single #[pymodule_export] use some_library::protocols;.
A protocol can only be exported by one module.
Since pyprotocol! requires the experimental-inspect feature, a crate that is also built without it puts the protocol and its export behind #[cfg(feature = "...")].
Constraints and limitations
- The
experimental-inspectfeature is required to generate the introspection fragments. - Lots of features are not implemented yet. See the related issue for a list of them.
- Introspection only works with Python modules declared with an inline Rust module. Modules declared using a function are not supported.
FromPyObject::INPUT_TYPEandIntoPyObject::OUTPUT_TYPEmust be implemented for PyO3 to get the proper input/output type annotations to use.- The generated stubs depend on the Python version the extension is built for.
For example, the
disjoint_basedecorator is imported fromtypingwhen targeting Python 3.15 or newer and fromtyping_extensionsotherwise. If you commit generated stubs to your repository, generate them with the oldest Python version you support (or with the matchingabi3-pyXYfeature) so that they are valid for every version. - PyO3 is not able to introspect the content of
#[pymodule]and#[pymodule_init]functions. If they are present, the module is tagged as incomplete using a fakedef __getattr__(name: str) -> Incomplete: ...function following best practices. Such a module also gets no__all__declaration, because the set of names it exports at runtime is not known. A#[pymodule_init]function declared without the module argument is exempt: it is not handed the module, so the module is taken to be complete and keeps its__all__. APython<'_>marker on its own does not count as the module argument.