Skip to content

Commit 2cc638b

Browse files
committed
Use into_pyresult_with in example
1 parent ec53a1f commit 2cc638b

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,10 @@ fn rust_ext(_py: Python, m: &PyModule) -> PyResult<()> {
118118
x: &PyArrayDyn<f64>,
119119
y: &PyArrayDyn<f64>,
120120
) -> PyResult<PyArrayDyn<f64>> {
121+
// you can convert numpy error into PyErr via ?
121122
let x = x.as_array()?;
122-
let y = y.as_array()?;
123+
// you can also specify your error context, via closure
124+
let y = y.as_array().into_pyresult_with(|| "y must be f64 array")?;
123125
Ok(axpy(a, x, y).to_pyarray(py).to_owned(py))
124126
}
125127

example/extensions/src/lib.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ extern crate numpy;
33
extern crate pyo3;
44

55
use ndarray::{ArrayD, ArrayViewD, ArrayViewMutD};
6-
use numpy::{PyArrayDyn, ToPyArray};
6+
use numpy::{IntoPyResult, PyArrayDyn, ToPyArray};
77
use pyo3::prelude::{pymodinit, PyModule, PyResult, Python};
88

99
#[pymodinit]
@@ -26,8 +26,10 @@ fn rust_ext(_py: Python, m: &PyModule) -> PyResult<()> {
2626
x: &PyArrayDyn<f64>,
2727
y: &PyArrayDyn<f64>,
2828
) -> PyResult<PyArrayDyn<f64>> {
29+
// you can convert numpy error into PyErr via ?
2930
let x = x.as_array()?;
30-
let y = y.as_array()?;
31+
// you can also specify your error context, via closure
32+
let y = y.as_array().into_pyresult_with(|| "y must be f64 array")?;
3133
Ok(axpy(a, x, y).to_pyarray(py).to_owned(py))
3234
}
3335

0 commit comments

Comments
 (0)