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
4 changes: 4 additions & 0 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ unsafe impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D> {
fn is_type_of(ob: &Bound<'_, PyAny>) -> bool {
Self::extract::<IgnoreError>(ob).is_ok()
}

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

impl<T: Element, D: Dimension> PyArray<T, D> {
Expand Down
20 changes: 20 additions & 0 deletions tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,26 @@ fn is_instance() {
});
}

#[test]
fn cast_exact_checks_dtype_and_shape() {
Python::attach(|py| {
let arr_f64 = PyArray2::<f64>::zeros(py, [3, 5], false);
let arr_f32 = PyArray2::<f32>::zeros(py, [3, 5], false);
let arr_f64_3d = PyArray::<f64, _>::zeros(py, [3, 5, 7], false);

// cast_exact should succeed when dtype and shape both match
assert!(arr_f64.as_any().cast_exact::<PyArray2<f64>>().is_ok());
assert!(arr_f32.as_any().cast_exact::<PyArray2<f32>>().is_ok());

// cast_exact should fail when dtype does not match
assert!(arr_f64.as_any().cast_exact::<PyArray2<f32>>().is_err());
assert!(arr_f32.as_any().cast_exact::<PyArray2<f64>>().is_err());

// cast_exact should fail when dimensionality does not match
assert!(arr_f64_3d.as_any().cast_exact::<PyArray2<f64>>().is_err());
});
}

#[test]
fn from_vec2() {
Python::attach(|py| {
Expand Down