pub struct PyArray<T, D>(_, _, _);
Expand description
A safe, static-typed interface for NumPy ndarray.
Memory location
- Case1: Constructed via
IntoPyArray
orfrom_vec
orfrom_owned_array
.
These methods don’t allocate memory and use Box<[T]>
as a internal buffer.
Please take care that you cannot use some destructive methods like resize
,
for this kind of array.
- Case2: Constructed via other methods, like
ToPyArray
orfrom_slice
orfrom_array
.
These methods allocate memory in Python’s private heap.
In both cases, PyArray is managed by Python GC. So you can neither retrieve it nor deallocate it manually.
Reference
Like new
, all constractor methods of PyArray
returns &PyArray
.
This design follows pyo3’s ownership concept.
Data type and Dimension
PyArray
has 2 type parametes T
and D
. T
represents its data type like
f32
, and D
represents its dimension.
All data types you can use implements Element.
Dimensions are represented by ndarray’s Dimension trait.
Typically, you can use Ix1, Ix2, ..
for fixed size arrays, and use IxDyn
for dynamic
dimensioned arrays. They’re re-exported from ndarray
crate.
You can also use various type aliases we provide, like PyArray1
or PyArrayDyn
.
To specify concrete dimension like 3×4×5
, you can use types which implements ndarray’s
IntoDimension
trait. Typically, you can use array(e.g. [3, 4, 5]
) or tuple(e.g. (3, 4, 5)
) as a dimension.
Example
use numpy::PyArray;
use ndarray::Array;
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0., 4., 1.).reshape([2, 2]).unwrap();
let array = array![[3., 4.], [5., 6.]];
assert_eq!(
array.dot(&pyarray.readonly().as_array()),
array![[8., 15.], [12., 23.]]
);
});
Implementations
sourceimpl<T, D> PyArray<T, D>
impl<T, D> PyArray<T, D>
sourcepub fn as_array_ptr(&self) -> *mut PyArrayObject
pub fn as_array_ptr(&self) -> *mut PyArrayObject
Gets a raw PyArrayObject
pointer.
sourcepub fn dtype(&self) -> &PyArrayDescr
pub fn dtype(&self) -> &PyArrayDescr
Returns dtype
of the array.
Counterpart of array.dtype
in Python.
Example
pyo3::Python::with_gil(|py| {
let array = numpy::PyArray::from_vec(py, vec![1, 2, 3i32]);
let dtype = array.dtype();
assert!(dtype.is_equiv_to(numpy::dtype::<i32>(py)));
});
sourcepub fn readonly(&self) -> PyReadonlyArray<'_, T, D>
pub fn readonly(&self) -> PyReadonlyArray<'_, T, D>
Returns a temporally unwriteable reference of the array.
sourcepub fn is_contiguous(&self) -> bool
pub fn is_contiguous(&self) -> bool
Returns true
if the internal data of the array is C-style contiguous
(default of numpy and ndarray) or Fortran-style contiguous.
Example
use pyo3::types::IntoPyDict;
pyo3::Python::with_gil(|py| {
let array = numpy::PyArray::arange(py, 0, 10, 1);
assert!(array.is_contiguous());
let locals = [("np", numpy::get_array_module(py).unwrap())].into_py_dict(py);
let not_contiguous: &numpy::PyArray1<f32> = py
.eval("np.zeros((3, 5), dtype='float32')[::2, 4]", Some(locals), None)
.unwrap()
.downcast()
.unwrap();
assert!(!not_contiguous.is_contiguous());
});
sourcepub fn is_fortran_contiguous(&self) -> bool
pub fn is_fortran_contiguous(&self) -> bool
Returns true
if the internal data of the array is Fortran-style contiguous.
sourcepub fn is_c_contiguous(&self) -> bool
pub fn is_c_contiguous(&self) -> bool
Returns true
if the internal data of the array is C-style contiguous.
sourcepub fn to_owned(&self) -> Py<Self>
pub fn to_owned(&self) -> Py<Self>
Get Py<PyArray>
from &PyArray
, which is the owned wrapper of PyObject.
You can use this method when you have to avoid lifetime annotation to your function args
or return types, like used with pyo3’s pymethod
.
Example
use numpy::PyArray1;
fn return_py_array() -> pyo3::Py<PyArray1<i32>> {
pyo3::Python::with_gil(|py| PyArray1::zeros(py, [5], false).to_owned())
}
let array = return_py_array();
pyo3::Python::with_gil(|py| {
assert_eq!(array.as_ref(py).readonly().as_slice().unwrap(), &[0, 0, 0, 0, 0]);
});
sourcepub unsafe fn from_owned_ptr(py: Python<'_>, ptr: *mut PyObject) -> &Self
pub unsafe fn from_owned_ptr(py: Python<'_>, ptr: *mut PyObject) -> &Self
Constructs PyArray
from raw Python object without incrementing reference counts.
Safety
Implementations must ensure the object does not get freed during 'py
and ensure that ptr
is of the correct type.
sourcepub unsafe fn from_borrowed_ptr<'py>(
py: Python<'py>,
ptr: *mut PyObject
) -> &'py Self
pub unsafe fn from_borrowed_ptr<'py>(
py: Python<'py>,
ptr: *mut PyObject
) -> &'py Self
Constructs PyArray from raw Python object and increments reference counts.
Safety
Implementations must ensure the object does not get freed during 'py
and ensure that ptr
is of the correct type.
Note that it must be safe to decrement the reference count of ptr.
sourcepub fn ndim(&self) -> usize
pub fn ndim(&self) -> usize
Returns the number of dimensions in the array.
Same as numpy.ndarray.ndim
Example
use numpy::PyArray3;
pyo3::Python::with_gil(|py| {
let arr = PyArray3::<f64>::zeros(py, [4, 5, 6], false);
assert_eq!(arr.ndim(), 3);
});
sourcepub fn strides(&self) -> &[isize]
pub fn strides(&self) -> &[isize]
Returns a slice which contains how many bytes you need to jump to the next row.
Same as numpy.ndarray.strides
Example
use numpy::PyArray3;
pyo3::Python::with_gil(|py| {
let arr = PyArray3::<f64>::zeros(py, [4, 5, 6], false);
assert_eq!(arr.strides(), &[240, 48, 8]);
});
sourcepub fn shape(&self) -> &[usize]
pub fn shape(&self) -> &[usize]
Returns a slice which contains dimmensions of the array.
Same as numpy.ndarray.shape
Example
use numpy::PyArray3;
pyo3::Python::with_gil(|py| {
let arr = PyArray3::<f64>::zeros(py, [4, 5, 6], false);
assert_eq!(arr.shape(), &[4, 5, 6]);
});
pub fn is_empty(&self) -> bool
sourceimpl<T: Element, D: Dimension> PyArray<T, D>
impl<T: Element, D: Dimension> PyArray<T, D>
sourcepub unsafe fn new<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> &Self where
ID: IntoDimension<Dim = D>,
pub unsafe fn new<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> &Self where
ID: IntoDimension<Dim = D>,
Creates a new uninitialized PyArray in python heap.
If is_fortran == true
, returns Fortran-order array. Else, returns C-order array.
Safety
The returned array will always be safe to be dropped as the elements must either
be trivially copyable or have DATA_TYPE == DataType::Object
, i.e. be pointers
into Python’s heap, which NumPy will automatically zero-initialize.
However, the elements themselves will not be valid and should only be accessed via raw pointers obtained via uget_raw.
All methods which produce references to the elements invoke undefined behaviour.
In particular, zero-initialized pointers are not valid instances of PyObject
.
Example
use numpy::PyArray3;
pyo3::Python::with_gil(|py| {
let arr = unsafe {
let arr = PyArray3::<i32>::new(py, [4, 5, 6], false);
for i in 0..4 {
for j in 0..5 {
for k in 0..6 {
arr.uget_raw([i, j, k]).write((i * j * k) as i32);
}
}
}
arr
};
assert_eq!(arr.shape(), &[4, 5, 6]);
});
sourcepub unsafe fn borrow_from_array<'py, S>(
array: &ArrayBase<S, D>,
container: &'py PyAny
) -> &'py Self where
S: Data<Elem = T>,
pub unsafe fn borrow_from_array<'py, S>(
array: &ArrayBase<S, D>,
container: &'py PyAny
) -> &'py Self where
S: Data<Elem = T>,
Creates a NumPy array backed by array
and ties its ownership to the Python object container
.
Safety
container
is set as a base object of the returned array which must not be dropped until container
is dropped.
Furthermore, array
must not be reallocated from the time this method is called and until container
is dropped.
Example
#[pyclass]
struct Owner {
array: Array1<f64>,
}
#[pymethods]
impl Owner {
#[getter]
fn array<'py>(this: &'py PyCell<Self>) -> &'py PyArray1<f64> {
let array = &this.borrow().array;
// SAFETY: The memory backing `array` will stay valid as long as this object is alive
// as we do not modify `array` in any way which would cause it to be reallocated.
unsafe { PyArray1::borrow_from_array(array, this) }
}
}
sourcepub fn zeros<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> &Self where
ID: IntoDimension<Dim = D>,
pub fn zeros<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> &Self where
ID: IntoDimension<Dim = D>,
Construct a new nd-dimensional array filled with 0.
If is_fortran
is true, then
a fortran order array is created, otherwise a C-order array is created.
For elements with DATA_TYPE == DataType::Object
, this will fill the array
with valid pointers to zero-valued Python integer objects.
See also PyArray_Zeros
Example
use numpy::PyArray2;
pyo3::Python::with_gil(|py| {
let pyarray: &PyArray2<usize> = PyArray2::zeros(py, [2, 2], false);
assert_eq!(pyarray.readonly().as_array(), array![[0, 0], [0, 0]]);
});
sourcepub unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
pub unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
Returns the immutable view of the internal data of PyArray
as slice.
Please consider the use of the safe alternative PyReadonlyArray::as_slice
.
Safety
If the internal array is not readonly and can be mutated from Python code, holding the slice might cause undefined behavior.
sourcepub unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
pub unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
Returns the view of the internal data of PyArray
as mutable slice.
Safety
If another reference to the internal data exists(e.g., &[T]
or ArrayView
),
it might cause undefined behavior.
sourcepub fn from_owned_array<'py>(py: Python<'py>, arr: Array<T, D>) -> &'py Self
pub fn from_owned_array<'py>(py: Python<'py>, arr: Array<T, D>) -> &'py Self
Constructs a PyArray
from ndarray::Array
This method uses the internal Vec
of the ndarray::Array
as the base object of the NumPy array.
Example
use ndarray::array;
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_owned_array(py, array![[1, 2], [3, 4]]);
assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
});
sourcepub unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
pub unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
Get the immutable reference of the specified element, with checking the passed index is valid.
Please consider the use of safe alternatives
(PyReadonlyArray::get
or get_owned
) instead of this.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
assert_eq!(*unsafe { arr.get([1, 0, 3]) }.unwrap(), 11);
});
Safety
If the internal array is not readonly and can be mutated from Python code, holding the slice might cause undefined behavior.
sourcepub unsafe fn uget<Idx>(&self, index: Idx) -> &T where
Idx: NpyIndex<Dim = D>,
pub unsafe fn uget<Idx>(&self, index: Idx) -> &T where
Idx: NpyIndex<Dim = D>,
Get the immutable reference of the specified element, without checking the passed index is valid.
See NpyIndex for what types you can use as index.
Safety
Passing an invalid index is undefined behavior. The element must also have been initialized. The elemet must also not be modified by Python code.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
assert_eq!(unsafe { *arr.uget([1, 0, 3]) }, 11);
});
sourcepub fn to_dyn(&self) -> &PyArray<T, IxDyn>
pub fn to_dyn(&self) -> &PyArray<T, IxDyn>
Get dynamic dimensioned array from fixed dimension array.
sourcepub fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
pub fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
Returns the copy of the internal data of PyArray
to Vec
.
Returns ErrorKind::NotContiguous
if the internal array is not contiguous.
See also as_slice
Example
use numpy::PyArray2;
use pyo3::types::IntoPyDict;
pyo3::Python::with_gil(|py| {
let locals = [("np", numpy::get_array_module(py).unwrap())].into_py_dict(py);
let array: &PyArray2<i64> = py
.eval("np.array([[0, 1], [2, 3]], dtype='int64')", Some(locals), None)
.unwrap()
.downcast()
.unwrap();
assert_eq!(array.to_vec().unwrap(), vec![0, 1, 2, 3]);
});
sourcepub fn from_array<'py, S>(py: Python<'py>, arr: &ArrayBase<S, D>) -> &'py Self where
S: Data<Elem = T>,
pub fn from_array<'py, S>(py: Python<'py>, arr: &ArrayBase<S, D>) -> &'py Self where
S: Data<Elem = T>,
Construct PyArray from ndarray::ArrayBase
.
This method allocates memory in Python’s heap via numpy api, and then copies all elements of the array there.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_array(py, &array![[1, 2], [3, 4]]);
assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
});
sourcepub unsafe fn as_array(&self) -> ArrayView<'_, T, D>
pub unsafe fn as_array(&self) -> ArrayView<'_, T, D>
Get the immutable view of the internal data of PyArray
, as
ndarray::ArrayView
.
Please consider the use of safe alternatives
(PyReadonlyArray::as_array
or to_array
) instead of this.
Safety
If the internal array is not readonly and can be mutated from Python code,
holding the ArrayView
might cause undefined behavior.
sourcepub unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
pub unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
Returns the internal array as ArrayViewMut
. See also as_array
.
Safety
If another reference to the internal data exists(e.g., &[T]
or ArrayView
),
it might cause undefined behavior.
sourcepub fn as_raw_array(&self) -> RawArrayView<T, D>
pub fn as_raw_array(&self) -> RawArrayView<T, D>
Returns the internal array as RawArrayView
enabling element access via raw pointers
sourcepub fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
pub fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
Returns the internal array as RawArrayViewMut
enabling element access via raw pointers
sourcepub fn to_owned_array(&self) -> Array<T, D>
pub fn to_owned_array(&self) -> Array<T, D>
Get a copy of PyArray
as
ndarray::Array
.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let py_array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
assert_eq!(
py_array.to_owned_array(),
array![[0, 1], [2, 3]]
)
});
sourceimpl<D: Dimension> PyArray<PyObject, D>
impl<D: Dimension> PyArray<PyObject, D>
sourcepub fn from_owned_object_array<'py, T>(
py: Python<'py>,
arr: Array<Py<T>, D>
) -> &'py Self
pub fn from_owned_object_array<'py, T>(
py: Python<'py>,
arr: Array<Py<T>, D>
) -> &'py Self
Constructs a PyArray
containing objects from ndarray::Array
This method uses the internal Vec
of the ndarray::Array
as the base object the NumPy array.
Example
use ndarray::array;
use pyo3::{pyclass, Py, Python};
use numpy::PyArray;
#[pyclass]
struct CustomElement {
foo: i32,
bar: f64,
}
Python::with_gil(|py| {
let array = array![
Py::new(py, CustomElement {
foo: 1,
bar: 2.0,
}).unwrap(),
Py::new(py, CustomElement {
foo: 3,
bar: 4.0,
}).unwrap(),
];
let pyarray = PyArray::from_owned_object_array(py, array);
assert!(pyarray.readonly().get(0).unwrap().as_ref(py).is_instance_of::<CustomElement>().unwrap());
});
sourceimpl<T: Element> PyArray<T, Ix1>
impl<T: Element> PyArray<T, Ix1>
sourcepub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> &'py Self
pub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> &'py Self
Construct one-dimension PyArray from slice.
Example
use numpy::PyArray;
let array = [1, 2, 3, 4, 5];
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_slice(py, &array);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
});
sourcepub fn from_exact_iter(
py: Python<'_>,
iter: impl ExactSizeIterator<Item = T>
) -> &Self
pub fn from_exact_iter(
py: Python<'_>,
iter: impl ExactSizeIterator<Item = T>
) -> &Self
Construct one-dimension PyArray from a type which implements
ExactSizeIterator
.
Example
use numpy::PyArray;
use std::collections::BTreeSet;
let vec = vec![1, 2, 3, 4, 5];
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_exact_iter(py, vec.iter().map(|&x| x));
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
});
sourcepub fn from_iter(py: Python<'_>, iter: impl IntoIterator<Item = T>) -> &Self
pub fn from_iter(py: Python<'_>, iter: impl IntoIterator<Item = T>) -> &Self
Construct one-dimension PyArray from a type which implements
IntoIterator
.
If no reliable size_hint
is available,
this method can allocate memory multiple time, which can hurt performance.
Example
use numpy::PyArray;
let set: std::collections::BTreeSet<u32> = [4, 3, 2, 5, 1].into_iter().cloned().collect();
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_iter(py, set);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
});
sourcepub fn resize(&self, new_elems: usize) -> PyResult<()>
pub fn resize(&self, new_elems: usize) -> PyResult<()>
Extends or trancates the length of 1 dimension PyArray.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 10, 1);
assert_eq!(pyarray.len(), 10);
pyarray.resize(100).unwrap();
assert_eq!(pyarray.len(), 100);
});
sourcepub unsafe fn iter<'py>(&'py self) -> PyResult<NpySingleIter<'py, T, ReadWrite>>
👎 Deprecated: The wrappers of the array iterator API are deprecated, please use ndarray’s ArrayBase::iter_mut
instead.
pub unsafe fn iter<'py>(&'py self) -> PyResult<NpySingleIter<'py, T, ReadWrite>>
The wrappers of the array iterator API are deprecated, please use ndarray’s ArrayBase::iter_mut
instead.
Iterates all elements of this array. See NpySingleIter for more.
Safety
The iterator will produce mutable references into the array which must not be aliased by other references for the life time of the iterator.
sourceimpl<T: Element> PyArray<T, Ix2>
impl<T: Element> PyArray<T, Ix2>
sourcepub fn from_vec2<'py>(
py: Python<'py>,
v: &[Vec<T>]
) -> Result<&'py Self, FromVecError>
pub fn from_vec2<'py>(
py: Python<'py>,
v: &[Vec<T>]
) -> Result<&'py Self, FromVecError>
Construct a two-dimension PyArray from Vec<Vec<T>>
.
This function checks all dimension of inner vec, and if there’s any vec
where its dimension differs from others, it returns ArrayCastError
.
Example
use numpy::PyArray;
let vec2 = vec![vec![1, 2, 3]; 2];
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_vec2(py, &vec2).unwrap();
assert_eq!(pyarray.readonly().as_array(), array![[1, 2, 3], [1, 2, 3]]);
assert!(PyArray::from_vec2(py, &[vec![1], vec![2, 3]]).is_err());
});
sourceimpl<T: Element> PyArray<T, Ix3>
impl<T: Element> PyArray<T, Ix3>
sourcepub fn from_vec3<'py>(
py: Python<'py>,
v: &[Vec<Vec<T>>]
) -> Result<&'py Self, FromVecError>
pub fn from_vec3<'py>(
py: Python<'py>,
v: &[Vec<Vec<T>>]
) -> Result<&'py Self, FromVecError>
Construct a three-dimension PyArray from Vec<Vec<Vec<T>>>
.
This function checks all dimension of inner vec, and if there’s any vec where its dimension differs from others, it returns error.
Example
use numpy::PyArray;
let vec3 = vec![vec![vec![1, 2]; 2]; 2];
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::from_vec3(py, &vec3).unwrap();
assert_eq!(
pyarray.readonly().as_array(),
array![[[1, 2], [1, 2]], [[1, 2], [1, 2]]]
);
assert!(PyArray::from_vec3(py, &[vec![vec![1], vec![]]]).is_err());
});
sourceimpl<T: Element, D> PyArray<T, D>
impl<T: Element, D> PyArray<T, D>
sourcepub fn copy_to<U: Element>(&self, other: &PyArray<U, D>) -> PyResult<()>
pub fn copy_to<U: Element>(&self, other: &PyArray<U, D>) -> PyResult<()>
Copies self into other
, performing a data-type conversion if necessary.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
let pyarray_i = unsafe { PyArray::<i64, _>::new(py, [3], false) };
assert!(pyarray_f.copy_to(pyarray_i).is_ok());
assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
});
sourcepub fn cast<'py, U: Element>(
&'py self,
is_fortran: bool
) -> PyResult<&'py PyArray<U, D>>
pub fn cast<'py, U: Element>(
&'py self,
is_fortran: bool
) -> PyResult<&'py PyArray<U, D>>
Cast the PyArray<T>
to PyArray<U>
, by allocating a new array.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
let pyarray_i = pyarray_f.cast::<i32>(false).unwrap();
assert!(pyarray_f.copy_to(pyarray_i).is_ok());
assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
});
sourcepub fn reshape<'py, ID, D2>(
&'py self,
dims: ID
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
pub fn reshape<'py, ID, D2>(
&'py self,
dims: ID
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
Construct a new array which has same values as self, same matrix order, but has different
dimensions specified by dims
.
Since a returned array can contain a same pointer as self, we highly recommend to drop an
old array, if this method returns Ok
.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let array = PyArray::from_exact_iter(py, 0..9);
let array = array.reshape([3, 3]).unwrap();
assert_eq!(array.readonly().as_array(), array![[0, 1, 2], [3, 4, 5], [6, 7, 8]]);
assert!(array.reshape([5]).is_err());
});
sourcepub fn reshape_with_order<'py, ID, D2>(
&'py self,
dims: ID,
order: NPY_ORDER
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
pub fn reshape_with_order<'py, ID, D2>(
&'py self,
dims: ID,
order: NPY_ORDER
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
Same as reshape, but you can change the order of returned matrix.
sourceimpl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1>
impl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1>
sourcepub fn arange(py: Python<'_>, start: T, stop: T, step: T) -> &Self
pub fn arange(py: Python<'_>, start: T, stop: T, step: T) -> &Self
Return evenly spaced values within a given interval. Same as numpy.arange.
See also PyArray_Arange.
Example
use numpy::PyArray;
pyo3::Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 2.0, 4.0, 0.5);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[2.0, 2.5, 3.0, 3.5]);
let pyarray = PyArray::arange(py, -2, 4, 3);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[-2, 1]);
});
Methods from Deref<Target = PyAny>
sourcepub fn downcast<T>(&self) -> Result<&T, PyDowncastError<'_>> where
T: for<'py> PyTryFrom<'py>,
pub fn downcast<T>(&self) -> Result<&T, PyDowncastError<'_>> where
T: for<'py> PyTryFrom<'py>,
Converts this PyAny
to a concrete Python type.
Examples
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyDict, PyList};
Python::with_gil(|py| {
let dict = PyDict::new(py);
assert!(dict.is_instance_of::<PyAny>().unwrap());
let any: &PyAny = dict.as_ref();
assert!(any.downcast::<PyDict>().is_ok());
assert!(any.downcast::<PyList>().is_err());
});
sourcepub fn is<T>(&self, other: &T) -> bool where
T: AsPyPointer,
pub fn is<T>(&self, other: &T) -> bool where
T: AsPyPointer,
Returns whether self
and other
point to the same object. To compare
the equality of two objects (the ==
operator), use eq
.
This is equivalent to the Python expression self is other
.
sourcepub fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> where
N: ToPyObject,
pub fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> where
N: ToPyObject,
Determines whether this object has the given attribute.
This is equivalent to the Python expression hasattr(self, attr_name)
.
sourcepub fn getattr<N>(&self, attr_name: N) -> Result<&PyAny, PyErr> where
N: ToPyObject,
pub fn getattr<N>(&self, attr_name: N) -> Result<&PyAny, PyErr> where
N: ToPyObject,
Retrieves an attribute value.
This is equivalent to the Python expression self.attr_name
.
sourcepub fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> where
N: ToBorrowedObject,
V: ToBorrowedObject,
pub fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> where
N: ToBorrowedObject,
V: ToBorrowedObject,
Sets an attribute value.
This is equivalent to the Python expression self.attr_name = value
.
sourcepub fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> where
N: ToPyObject,
pub fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> where
N: ToPyObject,
Deletes an attribute.
This is equivalent to the Python statement del self.attr_name
.
sourcepub fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> where
O: ToPyObject,
pub fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> where
O: ToPyObject,
Returns an Ordering
between self
and other
.
This is equivalent to the following Python code:
if self == other:
return Equal
elif a < b:
return Less
elif a > b:
return Greater
else:
raise TypeError("PyAny::compare(): All comparisons returned false")
Examples
use pyo3::prelude::*;
use pyo3::types::PyFloat;
use std::cmp::Ordering;
Python::with_gil(|py| -> PyResult<()> {
let a = PyFloat::new(py, 0_f64);
let b = PyFloat::new(py, 42_f64);
assert_eq!(a.compare(b)?, Ordering::Less);
Ok(())
})?;
It will return PyErr
for values that cannot be compared:
use pyo3::prelude::*;
use pyo3::types::{PyFloat, PyString};
Python::with_gil(|py| -> PyResult<()> {
let a = PyFloat::new(py, 0_f64);
let b = PyString::new(py, "zero");
assert!(a.compare(b).is_err());
Ok(())
})?;
sourcepub fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp
) -> Result<&PyAny, PyErr> where
O: ToPyObject,
pub fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp
) -> Result<&PyAny, PyErr> where
O: ToPyObject,
Tests whether two Python objects obey a given CompareOp
.
Depending on the value of compare_op
, this is equivalent to one of the
following Python expressions:
compare_op | Python expression |
---|---|
CompareOp::Eq | self == other |
CompareOp::Ne | self != other |
CompareOp::Lt | self < other |
CompareOp::Le | self <= other |
CompareOp::Gt | self > other |
CompareOp::Ge | self >= other |
Examples
use pyo3::class::basic::CompareOp;
use pyo3::prelude::*;
use pyo3::types::PyInt;
Python::with_gil(|py| -> PyResult<()> {
let a: &PyInt = 0_u8.into_py(py).into_ref(py).downcast()?;
let b: &PyInt = 42_u8.into_py(py).into_ref(py).downcast()?;
assert!(a.rich_compare(b, CompareOp::Le)?.is_true()?);
Ok(())
})?;
sourcepub fn lt<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn lt<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is less than another.
This is equivalent to the Python expression self < other
.
sourcepub fn le<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn le<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is less than or equal to another.
This is equivalent to the Python expression self <= other
.
sourcepub fn eq<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn eq<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is equal to another.
This is equivalent to the Python expression self == other
.
sourcepub fn ne<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn ne<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is not equal to another.
This is equivalent to the Python expression self != other
.
sourcepub fn gt<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn gt<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is greater than another.
This is equivalent to the Python expression self > other
.
sourcepub fn ge<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
pub fn ge<O>(&self, other: O) -> Result<bool, PyErr> where
O: ToPyObject,
Tests whether this object is greater than or equal to another.
This is equivalent to the Python expression self >= other
.
sourcepub fn is_callable(&self) -> bool
pub fn is_callable(&self) -> bool
Determines whether this object appears callable.
This is equivalent to Python’s callable()
function.
Examples
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let builtins = PyModule::import(py, "builtins")?;
let print = builtins.getattr("print")?;
assert!(print.is_callable());
Ok(())
})?;
This is equivalent to the Python statement assert callable(print)
.
Note that unless an API needs to distinguish between callable and non-callable objects, there is no point in checking for callability. Instead, it is better to just do the call and handle potential exceptions.
sourcepub fn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
pub fn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs)
.
sourcepub fn call0(&self) -> Result<&PyAny, PyErr>
pub fn call0(&self) -> Result<&PyAny, PyErr>
Calls the object without arguments.
This is equivalent to the Python expression self()
.
Examples
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let module = PyModule::import(py, "builtins")?;
let help = module.getattr("help")?;
help.call0()?;
Ok(())
})?;
This is equivalent to the Python expression help()
.
sourcepub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> Result<&PyAny, PyErr>
pub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> Result<&PyAny, PyErr>
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args)
.
Examples
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let module = PyModule::import(py, "operator")?;
let add = module.getattr("add")?;
let args = (1, 2);
let value = add.call1(args)?;
assert_eq!(value.extract::<i32>()?, 3);
Ok(())
})?;
This is equivalent to the following Python code:
from operator import add
value = add(1,2)
assert value == 3
sourcepub fn call_method(
&self,
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
pub fn call_method(
&self,
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
Calls a method on the object.
This is equivalent to the Python expression self.name(*args, **kwargs)
.
Examples
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyList};
Python::with_gil(|py| -> PyResult<()> {
let list = PyList::new(py, vec![3, 6, 5, 4, 7]);
let kwargs = vec![("reverse", true)].into_py_dict(py);
list.call_method("sort", (), Some(kwargs))?;
assert_eq!(list.extract::<Vec<i32>>()?, vec![7, 6, 5, 4, 3]);
Ok(())
})?;
This is equivalent to the following Python code:
my_list = [3, 6, 5, 4, 7]
my_list.sort(reverse = True)
assert my_list == [7, 6, 5, 4, 3]
sourcepub fn call_method0(&self, name: &str) -> Result<&PyAny, PyErr>
pub fn call_method0(&self, name: &str) -> Result<&PyAny, PyErr>
Calls a method on the object without arguments.
This is equivalent to the Python expression self.name()
.
Examples
use pyo3::prelude::*;
use pyo3::types::PyFloat;
use std::f64::consts::PI;
Python::with_gil(|py| -> PyResult<()> {
let pi = PyFloat::new(py, PI);
let ratio = pi.call_method0("as_integer_ratio")?;
let (a, b) = ratio.extract::<(u64, u64)>()?;
assert_eq!(a, 884_279_719_003_555);
assert_eq!(b, 281_474_976_710_656);
Ok(())
})?;
This is equivalent to the following Python code:
import math
a, b = math.pi.as_integer_ratio()
sourcepub fn call_method1(
&self,
name: &str,
args: impl IntoPy<Py<PyTuple>>
) -> Result<&PyAny, PyErr>
pub fn call_method1(
&self,
name: &str,
args: impl IntoPy<Py<PyTuple>>
) -> Result<&PyAny, PyErr>
Calls a method on the object with only positional arguments.
This is equivalent to the Python expression self.name(*args)
.
Examples
use pyo3::prelude::*;
use pyo3::types::PyList;
Python::with_gil(|py| -> PyResult<()> {
let list = PyList::new(py, vec![1, 3, 4]);
list.call_method1("insert", (1, 2))?;
assert_eq!(list.extract::<Vec<u8>>()?, [1, 2, 3, 4]);
Ok(())
})?;
This is equivalent to the following Python code:
list_ = [1,3,4]
list_.insert(1,2)
assert list_ == [1,2,3,4]
sourcepub fn is_true(&self) -> Result<bool, PyErr>
pub fn is_true(&self) -> Result<bool, PyErr>
Returns whether the object is considered to be true.
This is equivalent to the Python expression bool(self)
.
sourcepub fn is_none(&self) -> bool
pub fn is_none(&self) -> bool
Returns whether the object is considered to be None.
This is equivalent to the Python expression self is None
.
sourcepub fn is_empty(&self) -> Result<bool, PyErr>
pub fn is_empty(&self) -> Result<bool, PyErr>
Returns true if the sequence or mapping has a length of 0.
This is equivalent to the Python expression len(self) == 0
.
sourcepub fn get_item<K>(&self, key: K) -> Result<&PyAny, PyErr> where
K: ToBorrowedObject,
pub fn get_item<K>(&self, key: K) -> Result<&PyAny, PyErr> where
K: ToBorrowedObject,
Gets an item from the collection.
This is equivalent to the Python expression self[key]
.
sourcepub fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> where
K: ToBorrowedObject,
V: ToBorrowedObject,
pub fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> where
K: ToBorrowedObject,
V: ToBorrowedObject,
Sets a collection item value.
This is equivalent to the Python expression self[key] = value
.
sourcepub fn del_item<K>(&self, key: K) -> Result<(), PyErr> where
K: ToBorrowedObject,
pub fn del_item<K>(&self, key: K) -> Result<(), PyErr> where
K: ToBorrowedObject,
Deletes an item from the collection.
This is equivalent to the Python expression del self[key]
.
sourcepub fn iter(&self) -> Result<&PyIterator, PyErr>
pub fn iter(&self) -> Result<&PyIterator, PyErr>
Takes an object and returns an iterator for it.
This is typically a new iterator but if the argument is an iterator, this returns itself.
sourcepub fn get_type_ptr(&self) -> *mut PyTypeObject
pub fn get_type_ptr(&self) -> *mut PyTypeObject
Returns the Python type pointer for this object.
sourcepub fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError<'a>> where
D: PyTryFrom<'a>,
pub fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError<'a>> where
D: PyTryFrom<'a>,
Casts the PyObject to a concrete Python object type.
This can cast only to native Python types, not types implemented in Rust.
sourcepub fn extract<'a, D>(&'a self) -> Result<D, PyErr> where
D: FromPyObject<'a>,
pub fn extract<'a, D>(&'a self) -> Result<D, PyErr> where
D: FromPyObject<'a>,
Extracts some type from the Python object.
This is a wrapper function around FromPyObject::extract()
.
sourcepub fn get_refcnt(&self) -> isize
pub fn get_refcnt(&self) -> isize
Returns the reference count for the Python object.
sourcepub fn repr(&self) -> Result<&PyString, PyErr>
pub fn repr(&self) -> Result<&PyString, PyErr>
Computes the “repr” representation of self.
This is equivalent to the Python expression repr(self)
.
sourcepub fn str(&self) -> Result<&PyString, PyErr>
pub fn str(&self) -> Result<&PyString, PyErr>
Computes the “str” representation of self.
This is equivalent to the Python expression str(self)
.
sourcepub fn hash(&self) -> Result<isize, PyErr>
pub fn hash(&self) -> Result<isize, PyErr>
Retrieves the hash code of self.
This is equivalent to the Python expression hash(self)
.
sourcepub fn len(&self) -> Result<usize, PyErr>
pub fn len(&self) -> Result<usize, PyErr>
Returns the length of the sequence or mapping.
This is equivalent to the Python expression len(self)
.
sourcepub fn dir(&self) -> &PyList
pub fn dir(&self) -> &PyList
Returns the list of attributes of this object.
This is equivalent to the Python expression dir(self)
.
sourcepub fn is_instance(&self, typ: &PyType) -> Result<bool, PyErr>
pub fn is_instance(&self, typ: &PyType) -> Result<bool, PyErr>
Checks whether this object is an instance of type typ
.
This is equivalent to the Python expression isinstance(self, typ)
.
sourcepub fn is_instance_of<T>(&self) -> Result<bool, PyErr> where
T: PyTypeObject,
pub fn is_instance_of<T>(&self) -> Result<bool, PyErr> where
T: PyTypeObject,
Checks whether this object is an instance of type T
.
This is equivalent to the Python expression isinstance(self, T)
,
if the type T
is known at compile time.
Trait Implementations
sourceimpl<T, D> AsPyPointer for PyArray<T, D>
impl<T, D> AsPyPointer for PyArray<T, D>
sourceimpl<'py, T, D> AsRef<PyArray<T, D>> for PyReadonlyArray<'py, T, D>
impl<'py, T, D> AsRef<PyArray<T, D>> for PyReadonlyArray<'py, T, D>
sourceimpl<'py, T, D> From<&'py PyArray<T, D>> for PyReadonlyArray<'py, T, D>
impl<'py, T, D> From<&'py PyArray<T, D>> for PyReadonlyArray<'py, T, D>
sourcefn from(array: &'py PyArray<T, D>) -> PyReadonlyArray<'py, T, D>
fn from(array: &'py PyArray<T, D>) -> PyReadonlyArray<'py, T, D>
Performs the conversion.
sourceimpl<'py, T: Element, D: Dimension> FromPyObject<'py> for &'py PyArray<T, D>
impl<'py, T: Element, D: Dimension> FromPyObject<'py> for &'py PyArray<T, D>
sourceimpl<T, D> PyNativeType for PyArray<T, D>
impl<T, D> PyNativeType for PyArray<T, D>
sourceimpl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D>
impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D>
type AsRefTarget = Self
type AsRefTarget = Self
Utility type to make Py::as_ref work.
sourcefn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
PyTypeObject instance for this type.
sourcefn is_type_of(ob: &PyAny) -> bool
fn is_type_of(ob: &PyAny) -> bool
Checks if object
is an instance of this type or a subclass of this type.
sourcefn is_exact_type_of(object: &PyAny) -> bool
fn is_exact_type_of(object: &PyAny) -> bool
Checks if object
is an instance of this type.
sourceimpl<T, D> ToPyObject for PyArray<T, D>
impl<T, D> ToPyObject for PyArray<T, D>
impl<T, D> PyLayout<PyArray<T, D>> for PyArrayObject
impl<T, D> PySizedLayout<PyArray<T, D>> for PyArrayObject
Auto Trait Implementations
impl<T, D> !RefUnwindSafe for PyArray<T, D>
impl<T, D> !Send for PyArray<T, D>
impl<T, D> !Sync for PyArray<T, D>
impl<T, D> Unpin for PyArray<T, D> where
D: Unpin,
T: Unpin,
impl<T, D> UnwindSafe for PyArray<T, D> where
D: UnwindSafe,
T: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<'p, T> FromPyPointer<'p> for T where
T: 'p + PyNativeType,
impl<'p, T> FromPyPointer<'p> for T where
T: 'p + PyNativeType,
sourceunsafe fn from_owned_ptr_or_opt(
py: Python<'p>,
ptr: *mut PyObject
) -> Option<&'p T>
unsafe fn from_owned_ptr_or_opt(
py: Python<'p>,
ptr: *mut PyObject
) -> Option<&'p T>
Convert from an arbitrary PyObject
. Read more
sourceunsafe fn from_borrowed_ptr_or_opt(
_py: Python<'p>,
ptr: *mut PyObject
) -> Option<&'p T>
unsafe fn from_borrowed_ptr_or_opt(
_py: Python<'p>,
ptr: *mut PyObject
) -> Option<&'p T>
Convert from an arbitrary borrowed PyObject
. Read more
sourceunsafe fn from_owned_ptr_or_panic(
py: Python<'p>,
ptr: *mut PyObject
) -> &'p Self
unsafe fn from_owned_ptr_or_panic(
py: Python<'p>,
ptr: *mut PyObject
) -> &'p Self
Convert from an arbitrary PyObject
or panic. Read more
sourceunsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut PyObject) -> &'p Self
unsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut PyObject) -> &'p Self
Convert from an arbitrary PyObject
or panic. Read more
sourceunsafe fn from_owned_ptr_or_err(
py: Python<'p>,
ptr: *mut PyObject
) -> Result<&'p Self, PyErr>
unsafe fn from_owned_ptr_or_err(
py: Python<'p>,
ptr: *mut PyObject
) -> Result<&'p Self, PyErr>
Convert from an arbitrary PyObject
. Read more
sourceunsafe fn from_borrowed_ptr_or_panic(
py: Python<'p>,
ptr: *mut PyObject
) -> &'p Self
unsafe fn from_borrowed_ptr_or_panic(
py: Python<'p>,
ptr: *mut PyObject
) -> &'p Self
Convert from an arbitrary borrowed PyObject
. Read more
sourceimpl<'v, T> PyTryFrom<'v> for T where
T: PyTypeInfo + PyNativeType,
impl<'v, T> PyTryFrom<'v> for T where
T: PyTypeInfo + PyNativeType,
sourcefn try_from<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
fn try_from<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
Cast from a concrete Python object type to PyObject.
sourcefn try_from_exact<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
fn try_from_exact<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
Cast from a concrete Python object type to PyObject. With exact type check.
sourceimpl<T> PyTypeObject for T where
T: PyTypeInfo,
impl<T> PyTypeObject for T where
T: PyTypeInfo,
sourcefn type_object(py: Python<'_>) -> &PyType
fn type_object(py: Python<'_>) -> &PyType
Returns the safe abstraction over the type object.