How to make a Python package with multiple modules importing from Rust? #3261
|
I want to be able to do for Pure Rust project: from my_package.module1 import sum_as_string
from my_package.module2 import greetWhere can I read about it? I'm not that good at using maturin. |
Replies: 1 comment
|
This is really about how Python packages/modules work on top of your Rust extension. To make my_package/ Each .py file just needs to expose the relevant function — sum_as_string in module1.py, greet in module2.py. The init.py (can be empty) is what makes my_package a proper Python package. With maturin specifically, if your Rust code compiles into one extension module, you can keep this clean structure on the Python side by having each file import from your compiled Rust module internally and re-export the function. For example, module1.py could contain: from my_package._rust_module import sum_as_string That way your public API stays organized as my_package.module1.sum_as_string and my_package.module2.greet, even though the real implementation is in Rust. Maturin's docs cover this under "mixed Rust/Python projects" — worth checking that section for the exact pyproject.toml/build config needed to support this layout. |
This is really about how Python packages/modules work on top of your Rust extension. To make
from my_package.module1 import sum_as_stringandfrom my_package.module2 import greetwork, structure your package like this:my_package/
init.py
module1.py
module2.py
Each .py file just needs to expose the relevant function — sum_as_string in module1.py, greet in module2.py. The init.py (can be empty) is what makes my_package a proper Python package.
With maturin specifically, if your Rust code compiles into one extension module, you can keep this clean structure on the Python side by having each file import from your compiled Rust module internally and re-export the function. For example, module…