We should figure out how to use the very nice extract implementation that exists for PyArray instead of this; the cast here ignores the underlying extract error and just gives a generic (and in some cases nonsensical) error:
|
let array = obj.cast::<PyArray<T, D>>()?; |
You removed the underlying detailed error from the public API in #315. We should use its information here.
Repro:
use numpy::PyReadonlyArray2;
use pyo3::prelude::*;
use pyo3::types::PyAnyMethods;
fn main() -> PyResult<()> {
Python::attach(|py| {
// A numpy.ndarray with the wrong dtype (float64 instead of float32)
py.run(
c"import numpy as np; arr = np.zeros((2, 2), dtype=np.float64)",
None, None,
)?;
let arr = py.eval(c"arr", None, None)?;
// Extracting as PyReadonlyArray2<f32> fails because the dtype doesn’t match
let err = arr.extract::<PyReadonlyArray2<f32>>().unwrap_err();
println!("arr’s Python type: {}", arr.get_type().name()?);
println!("Error message: {err}");
Ok(())
})
}
Outputs:
arr’s Python type: ndarray
Error message: 'ndarray' object is not an instance of 'ndarray'
Cargo.toml
[package]
name = "numpy-cast-error-mre"
version = "0.1.0"
edition = "2024"
[dependencies]
numpy = "0.29.0"
pyo3 = { version = "0.29.0", features = ["auto-initialize"] }
We should figure out how to use the very nice
extractimplementation that exists forPyArrayinstead of this; thecasthere ignores the underlying extract error and just gives a generic (and in some cases nonsensical) error:rust-numpy/src/borrow/mod.rs
Line 246 in 4ef0102
You removed the underlying detailed error from the public API in #315. We should use its information here.
Repro:
Outputs:
Cargo.toml