Python Modules
You can create a module as follows:
The #[pymodule]
procedural macro attribute takes care of exporting the initialization function of your
module to Python. It can take as an argument the name of your module, which must be the name of the .so
or .pyd
file; the default is the Rust function's name.
If the name of the module (the default being the function name) does not match the name of the .so
or
.pyd
file, you will get an import error in Python with the following message:
ImportError: dynamic module does not define module export function (PyInit_name_of_your_module)
To import the module, either copy the shared library as described in the README
or use a tool, e.g. maturin develop
with maturin or
python setup.py develop
with setuptools-rust.
Documentation
The Rust doc comments of the module initialization function will be applied automatically as the Python docstring of your module.
import rust2py
print(rust2py.__doc__)
Which means that the above Python code will print This module is implemented in Rust.
.
Modules as objects
In Python, modules are first class objects. This means that you can store them as values or add them to dicts or other modules:
This way, you can create a module hierarchy within a single extension module.
It is not necessary to add #[pymodule]
on nested modules, this is only required on the top-level module.