https://github.com/pasqualemainolfi/rust2py
Design Python libraries in Rust
https://github.com/pasqualemainolfi/rust2py
Last synced: 2 months ago
JSON representation
Design Python libraries in Rust
- Host: GitHub
- URL: https://github.com/pasqualemainolfi/rust2py
- Owner: PasqualeMainolfi
- Created: 2023-10-09T09:47:25.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-10-15T14:00:44.000Z (over 1 year ago)
- Last Synced: 2023-10-16T15:19:52.128Z (over 1 year ago)
- Language: Rust
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# DESIGN PYTHON LIBRARIES IN RUST USING MATURIN AND PYO3
1. Install rust
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustc --version
```2. Create virtual env using conda or pyenv
```sh
conda create -n rustpy python=3.11
conda activate rustpy
```3. Install `maturin` from pypi
```sh
pip install maturin
```4. Create new project and select `pyo3` bindings
```sh
maturin new
cd
```5. Update pyo3 in `Cargo.toml` if needed and design your library in `src/lib.rs`
```sh
cargo search pyo3
```here is a `lib.rs` example
```rust
use pyo3::prelude::*;/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_in_rust(a: f64, b: f64) -> f64 {
a + b
}/// A Python module implemented in Rust.
#[pymodule]
fn module(py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_in_rust, m)?)?;
Ok(())
}
```note that the `pymodule` name must be the same in `` and in `Cargo.toml` (name = <`pymodule name`>)
6. Compile
compile without install package. Typing:
```sh
maturin build --release
```find .whl in `/target/wheels`
Also on macOS, you will need to rename the output (`/target/release/) from *.dylib to *.so. On Windows, you will need to rename the output from *.dll to *.pyd.compile and install package. Typing:
```sh
maturin develop --release
```7. create python project and test package
```sh
touch
```import the module created in the python script, and use it:
```python
importresult = >
```**References:**
- `pyo3` documentarion,
- `maturin` user guide,