Skip to content

Bound<PyArray>>, PyReadonlyArray and PyReadwriteArray all create useless extract messages on dtype/shape mismatch #561

Description

@flying-sheep

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"] }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions