Skip to content

Commit 251bfde

Browse files
authored
Add simple example for PyArray<PyObject>. (#339)
Add simple example for PyArray<PyObject>.
1 parent a445411 commit 251bfde

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

examples/simple/src/lib.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,21 @@ use numpy::{
77
PyReadwriteArray1, PyReadwriteArrayDyn,
88
};
99
use pyo3::{
10+
exceptions::PyIndexError,
1011
pymodule,
1112
types::{PyDict, PyModule},
12-
FromPyObject, PyAny, PyResult, Python,
13+
FromPyObject, PyAny, PyObject, PyResult, Python,
1314
};
1415

1516
#[pymodule]
1617
fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
18+
// example using generic PyObject
19+
fn head(x: ArrayViewD<'_, PyObject>) -> PyResult<PyObject> {
20+
x.get(0)
21+
.cloned()
22+
.ok_or_else(|| PyIndexError::new_err("array index out of range"))
23+
}
24+
1725
// example using immutable borrows producing a new array
1826
fn axpy(a: f64, x: ArrayViewD<'_, f64>, y: ArrayViewD<'_, f64>) -> ArrayD<f64> {
1927
a * &x + &y
@@ -34,6 +42,13 @@ fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
3442
&x + &y
3543
}
3644

45+
// wrapper of `head`
46+
#[pyfn(m)]
47+
#[pyo3(name = "head")]
48+
fn head_py(_py: Python<'_>, x: PyReadonlyArrayDyn<'_, PyObject>) -> PyResult<PyObject> {
49+
head(x.as_array())
50+
}
51+
3752
// wrapper of `axpy`
3853
#[pyfn(m)]
3954
#[pyo3(name = "axpy")]

examples/simple/tests/test_ext.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import numpy as np
2-
from rust_ext import axpy, conj, mult, extract, add_minutes_to_seconds, polymorphic_add
2+
from rust_ext import head, axpy, conj, mult, extract, add_minutes_to_seconds, polymorphic_add
3+
4+
5+
def test_head():
6+
x = np.array(['first', None, 42])
7+
first = head(x)
8+
assert first == 'first'
39

410

511
def test_axpy():

0 commit comments

Comments
 (0)