You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Bridging Python and Rust: A Practical Guide with PyO3
19
20
20
-
Sometimes Python just isn't fast enough, or you want to reuse some Rust code without rewriting it. [PyO3](https://pyo3.rs) makes it surprisingly easy to call Rust from Python (or less commonly vice-versa). Here’s how I created [pngme-python][1] crate, to expose my already existinv[pngme][2] Rust crate.
21
+
Sometimes Python just isn't fast enough, or you want to reuse some Rust code without rewriting it. [PyO3](https://pyo3.rs) makes it surprisingly easy to call Rust from Python (or less commonly vice-versa). Here’s how I created [pngme-python][1] crate, to expose my already existing[pngme][2] Rust crate as a python library.
21
22
22
23
## Project Structure
23
24
@@ -114,13 +115,13 @@ mod pngme_python {
114
115
115
116
The key parts of this implementation:
116
117
117
-
- The `#[pymodule]` macro creates a Python module
118
-
- Each `#[pyfunction]`exposes a Rust function to Python
119
-
- Rust error types are mapped to appropriate Python exceptions
118
+
- The `#[pymodule]` macro creates a Python module from the Rust module it encloses.
119
+
- Each `#[pyfunction]`within the Rust module adds a Rust function to Python the `#[pymodule]`.
120
+
-Each Rust error type must be handled and mapped to the appropriate Python exceptions.
120
121
121
122
## Step 2: Building and Packaging
122
123
123
-
[Maturin](https://github.com/PyO3/maturin)handles compiling the Rust code and packaging it as a Python wheel. Two configuration files control this process:
124
+
[Maturin](https://github.com/PyO3/maturin) handles compiling the Rust code and packaging it as a Python wheel. Two configuration files control this process:
124
125
125
126
**Cargo.toml**
126
127
```toml
@@ -157,7 +158,6 @@ features = ["pyo3/extension-module"]
157
158
Building is as simple as:
158
159
159
160
```bash
160
-
161
161
maturin develop
162
162
```
163
163
@@ -183,7 +183,7 @@ def test_pngme_encode():
183
183
184
184
## Step 4: Handling Errors
185
185
186
-
PyO3 lets you map Rust errors to Python exceptions, so Python users get idiomatic error messages:
186
+
PyO3 lets you map Rust errors to Python exceptions, so Python users get idiomatic error messages as shown below:
0 commit comments