Skip to content

Commit

Permalink
fix doc-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Icxolu committed Nov 20, 2024
1 parent 9253ad2 commit da18a72
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 50 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@ numpy = "0.22"

```rust
use numpy::{PyArray1, PyArrayMethods};
use pyo3::{types::{IntoPyDict, PyAnyMethods}, PyResult, Python};
use pyo3::{types::{IntoPyDict, PyAnyMethods}, PyResult, Python, ffi::c_str};

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

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

let readonly = pyarray.readonly();
Expand Down
15 changes: 8 additions & 7 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1055,17 +1055,18 @@ pub trait PyArrayMethods<'py, T, D>: PyUntypedArrayMethods<'py> {
///
/// ```
/// use numpy::{PyArray2, PyArrayMethods};
/// use pyo3::{Python, types::PyAnyMethods};
/// use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
///
/// # fn main() -> pyo3::PyResult<()> {
/// Python::with_gil(|py| {
/// let pyarray= py
/// .eval("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')", None, None)
/// .unwrap()
/// .downcast_into::<PyArray2<i64>>()
/// .unwrap();
/// .eval(c_str!("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')"), None, None)?
/// .downcast_into::<PyArray2<i64>>()?;
///
/// assert_eq!(pyarray.to_vec().unwrap(), vec![0, 1, 2, 3]);
/// });
/// assert_eq!(pyarray.to_vec()?, vec![0, 1, 2, 3]);
/// # Ok(())
/// })
/// # }
/// ```
fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
where
Expand Down
30 changes: 18 additions & 12 deletions src/borrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,17 @@
//!
//! ```rust
//! use numpy::{PyArray1, PyArrayMethods};
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
//!
//! # fn main() -> pyo3::PyResult<()> {
//! Python::with_gil(|py| {
//! let array = PyArray1::arange(py, 0.0, 10.0, 1.0);
//! let locals = [("array", array)].into_py_dict(py).unwrap();
//! let locals = [("array", array)].into_py_dict(py)?;
//!
//! let view1 = py.eval("array[:5]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
//! let view2 = py.eval("array[5:]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
//! let view3 = py.eval("array[::2]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
//! let view4 = py.eval("array[1::2]", None, Some(&locals)).unwrap().downcast_into::<PyArray1<f64>>().unwrap();
//! let view1 = py.eval(c_str!("array[:5]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
//! let view2 = py.eval(c_str!("array[5:]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
//! let view3 = py.eval(c_str!("array[::2]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
//! let view4 = py.eval(c_str!("array[1::2]"), None, Some(&locals))?.downcast_into::<PyArray1<f64>>()?;
//!
//! {
//! let _view1 = view1.readwrite();
Expand All @@ -83,7 +84,9 @@
//! let _view3 = view3.readwrite();
//! let _view4 = view4.readwrite();
//! }
//! });
//! # Ok(())
//! })
//! # }
//! ```
//!
//! The third example shows that some views are incorrectly rejected since the borrows are over-approximated.
Expand All @@ -92,22 +95,25 @@
//! # use std::panic::{catch_unwind, AssertUnwindSafe};
//! #
//! use numpy::{PyArray2, PyArrayMethods};
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
//! use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
//!
//! # fn main() -> pyo3::PyResult<()> {
//! Python::with_gil(|py| {
//! let array = PyArray2::<f64>::zeros(py, (10, 10), false);
//! let locals = [("array", array)].into_py_dict(py).unwrap();
//! let locals = [("array", array)].into_py_dict(py)?;
//!
//! let view1 = py.eval("array[:, ::3]", None, Some(&locals)).unwrap().downcast_into::<PyArray2<f64>>().unwrap();
//! let view2 = py.eval("array[:, 1::3]", None, Some(&locals)).unwrap().downcast_into::<PyArray2<f64>>().unwrap();
//! let view1 = py.eval(c_str!("array[:, ::3]"), None, Some(&locals))?.downcast_into::<PyArray2<f64>>()?;
//! let view2 = py.eval(c_str!("array[:, 1::3]"), None, Some(&locals))?.downcast_into::<PyArray2<f64>>()?;
//!
//! // A false conflict as the views do not actually share any elements.
//! let res = catch_unwind(AssertUnwindSafe(|| {
//! let _view1 = view1.readwrite();
//! let _view2 = view2.readwrite();
//! }));
//! assert!(res.is_err());
//! });
//! # Ok(())
//! })
//! # }
//! ```
//!
//! # Rationale
Expand Down
29 changes: 13 additions & 16 deletions src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,22 @@
//!
//! ```
//! use numpy::{datetime::{units, Datetime, Timedelta}, PyArray1, PyArrayMethods};
//! use pyo3::{Python, types::PyAnyMethods};
//! use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
//! # use pyo3::types::PyDict;
//!
//! # fn main() -> pyo3::PyResult<()> {
//! Python::with_gil(|py| {
//! # let locals = py
//! # .eval("{ 'np': __import__('numpy') }", None, None)
//! # .unwrap()
//! # .downcast_into::<PyDict>()
//! # .unwrap();
//! # .eval(c_str!("{ 'np': __import__('numpy') }"), None, None)?
//! # .downcast_into::<PyDict>()?;
//! #
//! let array = py
//! .eval(
//! "np.array([np.datetime64('2017-04-21')])",
//! c_str!("np.array([np.datetime64('2017-04-21')])"),
//! None,
//! Some(&locals),
//! )
//! .unwrap()
//! .downcast_into::<PyArray1<Datetime<units::Days>>>()
//! .unwrap();
//! )?
//! .downcast_into::<PyArray1<Datetime<units::Days>>>()?;
//!
//! assert_eq!(
//! array.get_owned(0).unwrap(),
Expand All @@ -38,19 +35,19 @@
//!
//! let array = py
//! .eval(
//! "np.array([np.datetime64('2022-03-29')]) - np.array([np.datetime64('2017-04-21')])",
//! c_str!("np.array([np.datetime64('2022-03-29')]) - np.array([np.datetime64('2017-04-21')])"),
//! None,
//! Some(&locals),
//! )
//! .unwrap()
//! .downcast_into::<PyArray1<Timedelta<units::Days>>>()
//! .unwrap();
//! )?
//! .downcast_into::<PyArray1<Timedelta<units::Days>>>()?;
//!
//! assert_eq!(
//! array.get_owned(0).unwrap(),
//! Timedelta::<units::Days>::from(1_803)
//! );
//! });
//! # Ok(())
//! })
//! # }
//! ```
//!
//! [datetime]: https://numpy.org/doc/stable/reference/arrays.datetime.html
Expand Down
15 changes: 8 additions & 7 deletions src/dtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,20 @@ pub use num_complex::{Complex32, Complex64};
///
/// ```
/// use numpy::{dtype, get_array_module, PyArrayDescr, PyArrayDescrMethods};
/// use numpy::pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
/// use numpy::pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
///
/// # fn main() -> pyo3::PyResult<()> {
/// Python::with_gil(|py| {
/// let locals = [("np", get_array_module(py).unwrap())].into_py_dict(py).unwrap();
/// let locals = [("np", get_array_module(py)?)].into_py_dict(py)?;
///
/// let dt = py
/// .eval("np.array([1, 2, 3.0]).dtype", Some(&locals), None)
/// .unwrap()
/// .downcast_into::<PyArrayDescr>()
/// .unwrap();
/// .eval(c_str!("np.array([1, 2, 3.0]).dtype"), Some(&locals), None)?
/// .downcast_into::<PyArrayDescr>()?;
///
/// assert!(dt.is_equiv_to(&dtype::<f64>(py)));
/// });
/// # Ok(())
/// })
/// # }
/// ```
///
/// [dtype]: https://numpy.org/doc/stable/reference/generated/numpy.dtype.html
Expand Down
13 changes: 7 additions & 6 deletions src/untyped_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,20 @@ pub trait PyUntypedArrayMethods<'py>: Sealed {
///
/// ```
/// use numpy::{PyArray1, PyUntypedArrayMethods};
/// use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python};
/// use pyo3::{types::{IntoPyDict, PyAnyMethods}, Python, ffi::c_str};
///
/// # fn main() -> pyo3::PyResult<()> {
/// Python::with_gil(|py| {
/// let array = PyArray1::arange(py, 0, 10, 1);
/// assert!(array.is_contiguous());
///
/// let view = py
/// .eval("array[::2]", None, Some(&[("array", array)].into_py_dict(py).unwrap()))
/// .unwrap()
/// .downcast_into::<PyArray1<i32>>()
/// .unwrap();
/// .eval(c_str!("array[::2]"), None, Some(&[("array", array)].into_py_dict(py)?))?
/// .downcast_into::<PyArray1<i32>>()?;
/// assert!(!view.is_contiguous());
/// });
/// # Ok(())
/// })
/// # }
/// ```
fn is_contiguous(&self) -> bool {
unsafe {
Expand Down

0 comments on commit da18a72

Please sign in to comment.