Skip to content

Commit d35c53a

Browse files
committed
fix doc-tests
1 parent 9253ad2 commit d35c53a

File tree

6 files changed

+64
-55
lines changed

6 files changed

+64
-55
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,15 +99,15 @@ numpy = "0.22"
9999

100100
```rust
101101
use numpy::{PyArray1, PyArrayMethods};
102-
use pyo3::{types::{IntoPyDict, PyAnyMethods}, PyResult, Python};
102+
use pyo3::{types::{IntoPyDict, PyAnyMethods}, PyResult, Python, ffi::c_str};
103103

104104
fn main() -> PyResult<()> {
105105
Python::with_gil(|py| {
106106
let np = py.import("numpy")?;
107107
let locals = [("np", np)].into_py_dict(py)?;
108108

109109
let pyarray = py
110-
.eval("np.absolute(np.array([-1, -2, -3], dtype='int32'))", Some(&locals), None)?
110+
.eval(c_str!("np.absolute(np.array([-1, -2, -3], dtype='int32'))"), Some(&locals), None)?
111111
.downcast_into::<PyArray1<i32>>()?;
112112

113113
let readonly = pyarray.readonly();

src/array.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,17 +1055,18 @@ pub trait PyArrayMethods<'py, T, D>: PyUntypedArrayMethods<'py> {
10551055
///
10561056
/// ```
10571057
/// use numpy::{PyArray2, PyArrayMethods};
1058-
/// use pyo3::{Python, types::PyAnyMethods};
1058+
/// use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
10591059
///
1060+
/// # fn main() -> pyo3::PyResult<()> {
10601061
/// Python::with_gil(|py| {
10611062
/// let pyarray= py
1062-
/// .eval("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')", None, None)
1063-
/// .unwrap()
1064-
/// .downcast_into::<PyArray2<i64>>()
1065-
/// .unwrap();
1063+
/// .eval(c_str!("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')"), None, None)?
1064+
/// .downcast_into::<PyArray2<i64>>()?;
10661065
///
1067-
/// assert_eq!(pyarray.to_vec().unwrap(), vec![0, 1, 2, 3]);
1068-
/// });
1066+
/// assert_eq!(pyarray.to_vec()?, vec![0, 1, 2, 3]);
1067+
/// # Ok(())
1068+
/// })
1069+
/// # }
10691070
/// ```
10701071
fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
10711072
where

src/borrow/mod.rs

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,17 @@
6363
//!
6464
//! ```rust
6565
//! use numpy::{PyArray1, PyArrayMethods};
66-
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
66+
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
6767
//!
68+
//! # fn main() -> pyo3::PyResult<()> {
6869
//! Python::with_gil(|py| {
6970
//! let array = PyArray1::arange(py, 0.0, 10.0, 1.0);
70-
//! let locals = [("array", array)].into_py_dict(py).unwrap();
71+
//! let locals = [("array", array)].into_py_dict(py)?;
7172
//!
72-
//! let view1 = py.eval("array[:5]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
73-
//! let view2 = py.eval("array[5:]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
74-
//! let view3 = py.eval("array[::2]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
75-
//! let view4 = py.eval("array[1::2]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
73+
//! let view1 = py.eval(c_str!("array[:5]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
74+
//! let view2 = py.eval(c_str!("array[5:]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
75+
//! let view3 = py.eval(c_str!("array[::2]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
76+
//! let view4 = py.eval(c_str!("array[1::2]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
7677
//!
7778
//! {
7879
//! let _view1 = view1.readwrite();
@@ -83,7 +84,9 @@
8384
//! let _view3 = view3.readwrite();
8485
//! let _view4 = view4.readwrite();
8586
//! }
86-
//! });
87+
//! # Ok(())
88+
//! })
89+
//! # }
8790
//! ```
8891
//!
8992
//! The third example shows that some views are incorrectly rejected since the borrows are over-approximated.
@@ -92,22 +95,25 @@
9295
//! # use std::panic::{catch_unwind, AssertUnwindSafe};
9396
//! #
9497
//! use numpy::{PyArray2, PyArrayMethods};
95-
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
98+
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
9699
//!
100+
//! # fn main() -> pyo3::PyResult<()> {
97101
//! Python::with_gil(|py| {
98102
//! let array = PyArray2::<f64>::zeros(py, (10, 10), false);
99-
//! let locals = [("array", array)].into_py_dict(py).unwrap();
103+
//! let locals = [("array", array)].into_py_dict(py)?;
100104
//!
101-
//! let view1 = py.eval("array[:, ::3]", None, Some(&locals)).unwrap().downcast_into::<PyArray2<f64>>().unwrap();
102-
//! let view2 = py.eval("array[:, 1::3]", None, Some(&locals)).unwrap().downcast_into::<PyArray2<f64>>().unwrap();
105+
//! let view1 = py.eval(c_str!("array[:, ::3]"), None, Some(&locals))?.downcast_into::<PyArray2<f64>>()?;
106+
//! let view2 = py.eval(c_str!("array[:, 1::3]"), None, Some(&locals))?.downcast_into::<PyArray2<f64>>()?;
103107
//!
104108
//! // A false conflict as the views do not actually share any elements.
105109
//! let res = catch_unwind(AssertUnwindSafe(|| {
106110
//! let _view1 = view1.readwrite();
107111
//! let _view2 = view2.readwrite();
108112
//! }));
109113
//! assert!(res.is_err());
110-
//! });
114+
//! # Ok(())
115+
//! })
116+
//! # }
111117
//! ```
112118
//!
113119
//! # Rationale
@@ -289,7 +295,7 @@ where
289295
///
290296
/// ```rust
291297
/// # use pyo3::prelude::*;
292-
/// use pyo3::py_run;
298+
/// use pyo3::{py_run, ffi::c_str};
293299
/// use numpy::{get_array_module, PyReadonlyArray2};
294300
/// use nalgebra::{MatrixView, Const, Dyn};
295301
///
@@ -305,17 +311,20 @@ where
305311
/// matrix.map(|matrix| matrix.sum())
306312
/// }
307313
///
314+
/// # fn main() -> pyo3::PyResult<()> {
308315
/// Python::with_gil(|py| {
309-
/// let np = py.eval("__import__('numpy')", None, None).unwrap();
310-
/// let sum_standard_layout = wrap_pyfunction!(sum_standard_layout)(py).unwrap();
311-
/// let sum_dynamic_strides = wrap_pyfunction!(sum_dynamic_strides)(py).unwrap();
316+
/// let np = py.eval(c_str!("__import__('numpy')"), None, None)?;
317+
/// let sum_standard_layout = wrap_pyfunction!(sum_standard_layout)(py)?;
318+
/// let sum_dynamic_strides = wrap_pyfunction!(sum_dynamic_strides)(py)?;
312319
///
313320
/// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2), order='F')) == 4.");
314321
/// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2, 2))[:,:,0]) is None");
315322
///
316323
/// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2), order='F')) == 4.");
317324
/// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2, 2))[:,:,0]) == 4.");
318-
/// });
325+
/// # Ok(())
326+
/// })
327+
/// # }
319328
/// ```
320329
#[doc(alias = "nalgebra")]
321330
pub fn try_as_matrix<R, C, RStride, CStride>(

src/datetime.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,25 +11,22 @@
1111
//!
1212
//! ```
1313
//! use numpy::{datetime::{units, Datetime, Timedelta}, PyArray1, PyArrayMethods};
14-
//! use pyo3::{Python, types::PyAnyMethods};
14+
//! use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
1515
//! # use pyo3::types::PyDict;
1616
//!
17+
//! # fn main() -> pyo3::PyResult<()> {
1718
//! Python::with_gil(|py| {
1819
//! # let locals = py
19-
//! # .eval("{ 'np': __import__('numpy') }", None, None)
20-
//! # .unwrap()
21-
//! # .downcast_into::<PyDict>()
22-
//! # .unwrap();
20+
//! # .eval(c_str!("{ 'np': __import__('numpy') }"), None, None)?
21+
//! # .downcast_into::<PyDict>()?;
2322
//! #
2423
//! let array = py
2524
//! .eval(
26-
//! "np.array([np.datetime64('2017-04-21')])",
25+
//! c_str!("np.array([np.datetime64('2017-04-21')])"),
2726
//! None,
2827
//! Some(&locals),
29-
//! )
30-
//! .unwrap()
31-
//! .downcast_into::<PyArray1<Datetime<units::Days>>>()
32-
//! .unwrap();
28+
//! )?
29+
//! .downcast_into::<PyArray1<Datetime<units::Days>>>()?;
3330
//!
3431
//! assert_eq!(
3532
//! array.get_owned(0).unwrap(),
@@ -38,19 +35,19 @@
3835
//!
3936
//! let array = py
4037
//! .eval(
41-
//! "np.array([np.datetime64('2022-03-29')]) - np.array([np.datetime64('2017-04-21')])",
38+
//! c_str!("np.array([np.datetime64('2022-03-29')]) - np.array([np.datetime64('2017-04-21')])"),
4239
//! None,
4340
//! Some(&locals),
44-
//! )
45-
//! .unwrap()
46-
//! .downcast_into::<PyArray1<Timedelta<units::Days>>>()
47-
//! .unwrap();
41+
//! )?
42+
//! .downcast_into::<PyArray1<Timedelta<units::Days>>>()?;
4843
//!
4944
//! assert_eq!(
5045
//! array.get_owned(0).unwrap(),
5146
//! Timedelta::<units::Days>::from(1_803)
5247
//! );
53-
//! });
48+
//! # Ok(())
49+
//! })
50+
//! # }
5451
//! ```
5552
//!
5653
//! [datetime]: https://numpy.org/doc/stable/reference/arrays.datetime.html

src/dtype.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,20 @@ pub use num_complex::{Complex32, Complex64};
3030
///
3131
/// ```
3232
/// use numpy::{dtype, get_array_module, PyArrayDescr, PyArrayDescrMethods};
33-
/// use numpy::pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
33+
/// use numpy::pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
3434
///
35+
/// # fn main() -> pyo3::PyResult<()> {
3536
/// Python::with_gil(|py| {
36-
/// let locals = [("np", get_array_module(py).unwrap())].into_py_dict(py).unwrap();
37+
/// let locals = [("np", get_array_module(py)?)].into_py_dict(py)?;
3738
///
3839
/// let dt = py
39-
/// .eval("np.array([1, 2, 3.0]).dtype", Some(&locals), None)
40-
/// .unwrap()
41-
/// .downcast_into::<PyArrayDescr>()
42-
/// .unwrap();
40+
/// .eval(c_str!("np.array([1, 2, 3.0]).dtype"), Some(&locals), None)?
41+
/// .downcast_into::<PyArrayDescr>()?;
4342
///
4443
/// assert!(dt.is_equiv_to(&dtype::<f64>(py)));
45-
/// });
44+
/// # Ok(())
45+
/// })
46+
/// # }
4647
/// ```
4748
///
4849
/// [dtype]: https://numpy.org/doc/stable/reference/generated/numpy.dtype.html

src/untyped_array.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,20 @@ pub trait PyUntypedArrayMethods<'py>: Sealed {
111111
///
112112
/// ```
113113
/// use numpy::{PyArray1, PyUntypedArrayMethods};
114-
/// use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
114+
/// use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
115115
///
116+
/// # fn main() -> pyo3::PyResult<()> {
116117
/// Python::with_gil(|py| {
117118
/// let array = PyArray1::arange(py, 0, 10, 1);
118119
/// assert!(array.is_contiguous());
119120
///
120121
/// let view = py
121-
/// .eval("array[::2]", None, Some(&[("array", array)].into_py_dict(py).unwrap()))
122-
/// .unwrap()
123-
/// .downcast_into::<PyArray1<i32>>()
124-
/// .unwrap();
122+
/// .eval(c_str!("array[::2]"), None, Some(&[("array", array)].into_py_dict(py)?))?
123+
/// .downcast_into::<PyArray1<i32>>()?;
125124
/// assert!(!view.is_contiguous());
126-
/// });
125+
/// # Ok(())
126+
/// })
127+
/// # }
127128
/// ```
128129
fn is_contiguous(&self) -> bool {
129130
unsafe {

0 commit comments

Comments
 (0)