Skip to content

Commit 1190fbe

Browse files
committed
fix: Don’t panic in when extracting PyReadwriteArray
1 parent 4ef0102 commit 1190fbe

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

‎src/borrow/mod.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ use std::ops::Deref;
175175
use ndarray::{
176176
ArrayView, ArrayViewMut, Dimension, IntoDimension, Ix0, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn,
177177
};
178-
use pyo3::{Borrowed, Bound, CastError, FromPyObject, PyAny, PyResult};
178+
use pyo3::{Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult};
179179

180180
use crate::array::{PyArray, PyArrayMethods};
181181
use crate::convert::NpyIndex;
@@ -240,11 +240,11 @@ where
240240
impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
241241
for PyReadonlyArray<'py, T, D>
242242
{
243-
type Error = CastError<'a, 'py>;
243+
type Error = PyErr;
244244

245245
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
246246
let array = obj.cast::<PyArray<T, D>>()?;
247-
Ok(array.readonly())
247+
Ok(array.try_readonly()?)
248248
}
249249
}
250250

@@ -483,11 +483,11 @@ where
483483
impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
484484
for PyReadwriteArray<'py, T, D>
485485
{
486-
type Error = CastError<'a, 'py>;
486+
type Error = PyErr;
487487

488488
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
489489
let array = obj.cast::<PyArray<T, D>>()?;
490-
Ok(array.readwrite())
490+
Ok(array.try_readwrite()?)
491491
}
492492
}
493493

‎tests/borrow.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use numpy::{
66
};
77
use pyo3::{
88
ffi::c_str,
9-
py_run, pyclass, pymethods,
9+
pyclass, pymethods,
1010
types::{IntoPyDict, PyAnyMethods},
1111
Py, Python,
1212
};
@@ -97,16 +97,17 @@ impl Borrower {
9797
}
9898

9999
#[test]
100-
#[should_panic(expected = "AlreadyBorrowed")]
101100
fn borrows_span_frames() {
102101
Python::attach(|py| {
103102
let borrower = Py::new(py, Borrower).unwrap();
103+
let borrower = borrower.bind(py);
104104

105105
let array = PyArray::<f64, _>::zeros(py, (1, 2, 3), false);
106106

107107
let _exclusive = array.readwrite();
108108

109-
py_run!(py, borrower array, "borrower.exclusive(array)");
109+
let locals = [("borrower", borrower.as_any()), ("array", array.as_any())].into_py_dict(py).unwrap();
110+
py.run(c"borrower.exclusive(array)", Some(&locals), None).expect_err("already borrowed");
110111
});
111112
}
112113

0 commit comments

Comments
 (0)