Skip to content

Commit 6e8425d

Browse files
committed
Add a documentation about slice to PyArray conversion
1 parent 550efd0 commit 6e8425d

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/convert.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,27 @@ where
7171
/// elements there**.
7272
/// # Example
7373
/// ```
74-
/// # fn main() {
7574
/// use numpy::{PyArray, ToPyArray};
7675
/// let gil = pyo3::Python::acquire_gil();
7776
/// let py_array = vec![1, 2, 3].to_pyarray(gil.python());
7877
/// assert_eq!(py_array.as_slice().unwrap(), &[1, 2, 3]);
79-
/// # }
78+
/// ```
79+
///
80+
/// This method converts a not-contiguous array to C-order contiguous array.
81+
/// # Example
82+
/// ```
83+
/// use numpy::{PyArray, ToPyArray};
84+
/// use ndarray::{arr3, s};
85+
/// let gil = pyo3::Python::acquire_gil();
86+
/// let py = gil.python();
87+
/// let a = arr3(&[[[ 1, 2, 3], [ 4, 5, 6]],
88+
/// [[ 7, 8, 9], [10, 11, 12]]]);
89+
/// let slice = a.slice(s![.., 0..1, ..]);
90+
/// let sliced = arr3(&[[[ 1, 2, 3]],
91+
/// [[ 7, 8, 9]]]);
92+
/// let py_slice = slice.to_pyarray(py);
93+
/// assert_eq!(py_slice.as_array(), sliced);
94+
/// pyo3::py_run!(py, py_slice, "assert py_slice.flags['C_CONTIGUOUS']");
8095
/// ```
8196
pub trait ToPyArray {
8297
type Item: TypeNum;

tests/to_py.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ fn forder_to_pyarray() {
117117
let fortran_matrix = matrix.reversed_axes();
118118
let fmat_py = fortran_matrix.to_pyarray(py);
119119
assert_eq!(fmat_py.as_array(), array![[0, 2, 4, 6], [1, 3, 5, 7]],);
120+
pyo3::py_run!(py, fmat_py, "assert fmat_py.flags['F_CONTIGUOUS']")
120121
}
121122

122123
#[test]
@@ -127,4 +128,16 @@ fn slice_to_pyarray() {
127128
let slice = matrix.slice(s![1..4; -1, ..]);
128129
let slice_py = slice.to_pyarray(py);
129130
assert_eq!(slice_py.as_array(), array![[6, 7], [4, 5], [2, 3]],);
131+
pyo3::py_run!(py, slice_py, "assert slice_py.flags['C_CONTIGUOUS']")
132+
}
133+
134+
#[test]
135+
fn forder_into_pyarray() {
136+
let gil = pyo3::Python::acquire_gil();
137+
let py = gil.python();
138+
let matrix = Array2::from_shape_vec([4, 2], vec![0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
139+
let fortran_matrix = matrix.reversed_axes();
140+
let fmat_py = fortran_matrix.into_pyarray(py);
141+
assert_eq!(fmat_py.as_array(), array![[0, 2, 4, 6], [1, 3, 5, 7]],);
142+
pyo3::py_run!(py, fmat_py, "assert fmat_py.flags['F_CONTIGUOUS']")
130143
}

0 commit comments

Comments
 (0)