Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Changelog

- Unreleased
- `PyReadonlyArray`/`PyReadwriteArray` extraction now returns a `PyErr` which reports the actual dtype/dimensionality mismatch instead of nonsensical `CastError` messages like “'ndarray' is not an instance of 'ndarray'” ([#562](https://github.com/PyO3/rust-numpy/pull/562))

- v0.29.0
- Fix PyArray_DTypeMeta definition when Py_LIMITED_API is disabled ([#532](https://github.com/PyO3/rust-numpy/pull/532))
Expand Down
14 changes: 7 additions & 7 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use num_traits::AsPrimitive;
use pyo3::{
ffi,
types::{DerefToPyAny, PyModule},
Bound, CastError, Py, PyAny, PyErr, PyResult, PyTypeCheck, PyTypeInfo, Python,
Borrowed, Bound, CastError, Py, PyAny, PyErr, PyResult, PyTypeCheck, PyTypeInfo, Python,
};

use crate::borrow::{PyReadonlyArray, PyReadwriteArray};
Expand Down Expand Up @@ -132,27 +132,27 @@ unsafe impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D> {
}

fn is_type_of(ob: &Bound<'_, PyAny>) -> bool {
Self::extract::<IgnoreError>(ob, npyffi::PyArray_Check).is_ok()
Self::extract::<IgnoreError>(ob.as_borrowed(), npyffi::PyArray_Check).is_ok()
}

fn is_exact_type_of(ob: &Bound<'_, PyAny>) -> bool {
Self::extract::<IgnoreError>(ob, npyffi::PyArray_CheckExact).is_ok()
Self::extract::<IgnoreError>(ob.as_borrowed(), npyffi::PyArray_CheckExact).is_ok()
}
}

impl<T: Element, D: Dimension> PyArray<T, D> {
fn extract<'a, 'py, E>(
ob: &'a Bound<'py, PyAny>,
pub(crate) fn extract<'a, 'py, E>(
ob: Borrowed<'a, 'py, PyAny>,
check: unsafe fn(Python<'py>, *mut ffi::PyObject) -> c_int,
) -> Result<&'a Bound<'py, Self>, E>
) -> Result<Borrowed<'a, 'py, Self>, E>
where
E: From<CastError<'a, 'py>> + From<DimensionalityError> + From<TypeError<'py>>,
{
// Check if the object is an array.
let array = unsafe {
if check(ob.py(), ob.as_ptr()) == 0 {
return Err(CastError::new(
ob.as_borrowed(),
ob,
<Self as PyTypeCheck>::classinfo_object(ob.py()),
)
.into());
Expand Down
48 changes: 42 additions & 6 deletions src/borrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,13 @@ use std::ops::Deref;
use ndarray::{
ArrayView, ArrayViewMut, Dimension, IntoDimension, Ix0, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn,
};
use pyo3::{Borrowed, Bound, CastError, FromPyObject, PyAny, PyResult};
use pyo3::{Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult};

use crate::array::{PyArray, PyArrayMethods};
use crate::convert::NpyIndex;
use crate::dtype::Element;
use crate::error::{AsSliceError, BorrowError};
use crate::npyffi;
use crate::npyffi::flags;
use crate::untyped_array::PyUntypedArrayMethods;

Expand Down Expand Up @@ -240,10 +241,10 @@ where
impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
for PyReadonlyArray<'py, T, D>
{
type Error = CastError<'a, 'py>;
type Error = PyErr;

fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
let array = obj.cast::<PyArray<T, D>>()?;
let array = PyArray::<T, D>::extract::<PyErr>(obj, npyffi::PyArray_Check)?;
Ok(array.readonly())
}
}
Expand Down Expand Up @@ -483,10 +484,10 @@ where
impl<'a, 'py, T: Element + 'a, D: Dimension + 'a> FromPyObject<'a, 'py>
for PyReadwriteArray<'py, T, D>
{
type Error = CastError<'a, 'py>;
type Error = PyErr;

fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
let array = obj.cast::<PyArray<T, D>>()?;
let array = PyArray::<T, D>::extract::<PyErr>(obj, npyffi::PyArray_Check)?;
Ok(array.readwrite())
}
}
Expand Down Expand Up @@ -675,7 +676,10 @@ where
mod tests {
use super::*;

use pyo3::{types::IntoPyDict, Python};
use pyo3::{
types::{IntoPyDict, PyAnyMethods},
Python,
};

use crate::array::PyArray1;
use pyo3::ffi::c_str;
Expand Down Expand Up @@ -743,4 +747,36 @@ mod tests {
assert!(exclusive.resize(10).is_ok());
});
}

#[test]
fn extraction_reports_dtype_mismatch() {
Python::attach(|py| {
let array = PyArray::<f64, _>::zeros(py, (2, 2), false);
let any = array.as_any();

let err = any.extract::<PyReadonlyArray2<'_, f32>>().unwrap_err();
let msg = err.to_string();
assert_eq!(msg, "TypeError: type mismatch:\n from=float64, to=float32");

let err = any.extract::<PyReadwriteArray2<'_, f32>>().unwrap_err();
let msg = err.to_string();
assert_eq!(msg, "TypeError: type mismatch:\n from=float64, to=float32");
});
}

#[test]
fn extraction_reports_dimensionality_mismatch() {
Python::attach(|py| {
let array = PyArray::<f64, _>::zeros(py, (2, 2), false);
let any = array.as_any();

let err = any.extract::<PyReadonlyArray3<'_, f64>>().unwrap_err();
let msg = err.to_string();
assert_eq!(msg, "TypeError: dimensionality mismatch:\n from=2, to=3");

let err = any.extract::<PyReadwriteArray3<'_, f64>>().unwrap_err();
let msg = err.to_string();
assert_eq!(msg, "TypeError: dimensionality mismatch:\n from=2, to=3");
});
}
}