rust-numpy icon indicating copy to clipboard operation
rust-numpy copied to clipboard

Mismatched behavior between PyArrayLike1 and PyArrayLike2 when used with floats

Open mattiapenati opened this issue 1 month ago • 0 comments

This pull request attempts to resolve issue #444.

Current behavior

When PyArrayLike1<f32, TypeMustMatch> is used, arrays constructed using np.array([...], dtype='float64') are converted implicitly to f32. This results in a new allocation and a truncation error.

Conversely, PyArrayLike2<f32, TypeMustMatch> behaves differently: arrays constructed using np.array([[...], ...], dtype='float64') are not accepted as valid values.

I think the current behavior creates confusion and is not consistent with the current documentation, which states:

Depending on whether TypeMustMatch or AllowTypeChange is used for the C type parameter, the element type must either match the specific type T exactly or will be cast to it by NumPy’s asarray.

New behavior

The condition in the following portion of code has been changed to avoid the implicit conversion introduced by Borrowed::extract call. The conversion should be performed only when the choice of D allows type changes or the input object is not a numpy ndarray.

https://github.com/PyO3/rust-numpy/blob/78d5e8d2aec80f0a3568c471bc69976642b129c4/src/array_like.rs#L154-L163

mattiapenati avatar Dec 10 '25 22:12 mattiapenati