From e21833ec1b67e935b3bba899dfd1ec6726a27a94 Mon Sep 17 00:00:00 2001 From: "Philipp A." Date: Mon, 20 Jul 2026 13:10:14 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20Don=E2=80=99t=20panic=20in=20when=20extr?= =?UTF-8?q?acting=20PyReadwriteArray?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/borrow/mod.rs | 4 ++-- tests/borrow.rs | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/borrow/mod.rs b/src/borrow/mod.rs index 40f38ee50..f0aa2405b 100644 --- a/src/borrow/mod.rs +++ b/src/borrow/mod.rs @@ -245,7 +245,7 @@ impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py> fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result { let array = PyArray::::extract::(obj, npyffi::PyArray_Check)?; - Ok(array.readonly()) + Ok(array.try_readonly()?) } } @@ -488,7 +488,7 @@ impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py> fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result { let array = PyArray::::extract::(obj, npyffi::PyArray_Check)?; - Ok(array.readwrite()) + Ok(array.try_readwrite()?) } } diff --git a/tests/borrow.rs b/tests/borrow.rs index 52c1ad8fb..6391dbf79 100644 --- a/tests/borrow.rs +++ b/tests/borrow.rs @@ -6,7 +6,7 @@ use numpy::{ }; use pyo3::{ ffi::c_str, - py_run, pyclass, pymethods, + pyclass, pymethods, types::{IntoPyDict, PyAnyMethods}, Py, Python, }; @@ -97,16 +97,20 @@ impl Borrower { } #[test] -#[should_panic(expected = "AlreadyBorrowed")] fn borrows_span_frames() { Python::attach(|py| { let borrower = Py::new(py, Borrower).unwrap(); + let borrower = borrower.bind(py); let array = PyArray::::zeros(py, (1, 2, 3), false); let _exclusive = array.readwrite(); - py_run!(py, borrower array, "borrower.exclusive(array)"); + let locals = [("borrower", borrower.as_any()), ("array", array.as_any())] + .into_py_dict(py) + .unwrap(); + py.run(c"borrower.exclusive(array)", Some(&locals), None) + .expect_err("already borrowed"); }); }