Skip to content

Remove extraction from Vec for PyArrayLikeDyn #496

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion src/array_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ where

let py = ob.py();

if matches!(D::NDIM, None | Some(1)) {
if matches!(D::NDIM, Some(1)) {
if let Ok(vec) = ob.extract::<Vec<T>>() {
let array = Array1::from(vec)
.into_dimensionality()
Expand Down
28 changes: 26 additions & 2 deletions tests/array_like.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use ndarray::array;
use numpy::{get_array_module, AllowTypeChange, PyArrayLike1, PyArrayLike2, PyArrayLikeDyn};
use numpy::{
get_array_module, AllowTypeChange, PyArrayLike1, PyArrayLike2, PyArrayLikeDyn,
PyUntypedArrayMethods,
};
use pyo3::{
ffi::c_str,
types::{IntoPyDict, PyAnyMethods, PyDict},
Expand Down Expand Up @@ -105,7 +108,9 @@ fn convert_1d_list_on_extract() {
Python::with_gil(|py| {
let py_list = py.eval(c_str!("[1,2,3,4]"), None, None).unwrap();
let extracted_array_1d = py_list.extract::<PyArrayLike1<'_, u32>>().unwrap();
let extracted_array_dyn = py_list.extract::<PyArrayLikeDyn<'_, f64>>().unwrap();
let extracted_array_dyn = py_list
.extract::<PyArrayLikeDyn<'_, f64, AllowTypeChange>>()
.unwrap();

assert_eq!(array![1, 2, 3, 4], extracted_array_1d.as_array());
assert_eq!(
Expand All @@ -115,6 +120,25 @@ fn convert_1d_list_on_extract() {
});
}

#[test]
fn preserve_trailing_singleton_dims() {
Python::with_gil(|py| {
let locals = get_np_locals(py);
let py_array = py
.eval(
c_str!("np.array([[1], [2], [3]], dtype='int32')"),
Some(&locals),
None,
)
.unwrap();
let extracted_array = py_array
.extract::<PyArrayLikeDyn<'_, f64, AllowTypeChange>>()
.unwrap();

assert_eq!(extracted_array.shape(), &[3, 1]);
})
}

#[test]
fn unsafe_cast_shall_fail() {
Python::with_gil(|py| {
Expand Down