liveBook · Manning

PyModule

As explained in Refactoring to Rust

PyModule is a PyO3 type representing a Python module exposed through the Python interpreter API.

PyModule is a PyO3 type representing the Python module created through the interpreter API. A #[pymodule] function receives an &PyModule even when it does not otherwise use the value. section 6.4

Use the module handle to expose Rust functions to Python. After marking sum with #[pyfunction], call m.add_function(wrap_pyfunction!(sum, m)?)? inside the initializer. section 6.4

Registering a function

The initializer returns PyResult<()> and adds sum to the extension module: m.add_function(wrap_pyfunction!(sum, m)?)?; Python can then call rust_json.sum(...).

How Refactoring to Rust covers it

How deep it goes
Explains the required initializer parameter and registration call, but stops short of PyModule internals.
Examples
Uses the rust_json extension to register sum and call it from Python with JSON input.
What it assumes
Assumes basic Rust functions and Python imports while introducing PyO3’s module initializer requirements incrementally.
What you can do after
Build it from scratch by defining a PyO3 module initializer and registering Rust functions through its PyModule handle.
How it connects
Connects PyModule with PyO3, the pymodule attribute, pyfunction attribute, PyResult, and Python extension modules.

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.