Struct numpy::PyReadonlyArray[][src]

pub struct PyReadonlyArray<'py, T, D> { /* fields omitted */ }

Readonly reference of PyArray.

This struct ensures that the internal array is not writeable while holding PyReadonlyArray. We use a simple trick for this: modifying the internal flag of the array when creating PyReadonlyArray and recover the original flag when it drops.

So, importantly, it does not recover the original flag when it does not drop (e.g., by the use of IntoPy::intopy or std::mem::forget) and then the internal array remains readonly.

Example

In this example, we get a ‘temporal’ readonly array and the internal array becomes writeble again after it drops.

use numpy::{PyArray, npyffi::NPY_ARRAY_WRITEABLE};
pyo3::Python::with_gil(|py| {
    let py_array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
    {
       let readonly = py_array.readonly();
       // The internal array is not writeable now.
       pyo3::py_run!(py, py_array, "assert not py_array.flags['WRITEABLE']");
    }
    // After the `readonly` drops, the internal array gets writeable again.
    pyo3::py_run!(py, py_array, "assert py_array.flags['WRITEABLE']");
});

However, if we convert the PyReadonlyArray directly into PyObject, the internal array remains readonly.

use numpy::{PyArray, npyffi::NPY_ARRAY_WRITEABLE};
use pyo3::{IntoPy, PyObject, Python};
pyo3::Python::with_gil(|py| {
    let py_array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
    let obj: PyObject = {
       let readonly = py_array.readonly();
       // The internal array is not writeable now.
       pyo3::py_run!(py, py_array, "assert not py_array.flags['WRITEABLE']");
       readonly.into_py(py)
    };
    // The internal array remains readonly.
    pyo3::py_run!(py, py_array, "assert py_array.flags['WRITEABLE']");
});

Implementations

impl<'py, T: Element, D: Dimension> PyReadonlyArray<'py, T, D>[src]

pub fn as_slice(&self) -> Result<&[T], NotContiguousError>[src]

Returns the immutable view of the internal data of PyArray as slice.

Returns ErrorKind::NotContiguous if the internal array is not contiguous.

Example

use numpy::{PyArray, PyArray1};
use pyo3::types::IntoPyDict;
pyo3::Python::with_gil(|py| {
    let py_array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
    let readonly = py_array.readonly();
    assert_eq!(readonly.as_slice().unwrap(), &[0, 1, 2, 3]);
    let locals = [("np", numpy::get_array_module(py).unwrap())].into_py_dict(py);
    let not_contiguous: &PyArray1<i32> = py
        .eval("np.arange(10)[::2]", Some(locals), None)
        .unwrap()
        .downcast()
        .unwrap();
    assert!(not_contiguous.readonly().as_slice().is_err());
});

pub fn as_array(&self) -> ArrayView<'_, T, D>[src]

Get the immutable view of the internal data of PyArray, as ndarray::ArrayView.

Example

use numpy::PyArray;
pyo3::Python::with_gil(|py| {
    let array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
    let readonly = array.readonly();
    assert_eq!(readonly.as_array(), array![[0, 1], [2, 3]]);
});

pub fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>[src]

Get an immutable reference of the specified element, with checking the passed index is valid.

See NpyIndex for what types you can use as index.

If you pass an invalid index to this function, it returns None.

Example

use numpy::PyArray;
pyo3::Python::with_gil(|py| {
    let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap().readonly();
    assert_eq!(*arr.get([1, 0, 3]).unwrap(), 11);
    assert!(arr.get([2, 0, 3]).is_none());
});

For fixed dimension arrays, passing an index with invalid dimension causes compile error.

use numpy::PyArray;
pyo3::Python::with_gil(|py| {
    let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap().readonly();
    let a = arr.get([1, 2]); // Compile Error!
});

However, for dinamic arrays, we cannot raise a compile error and just returns None.

use numpy::PyArray;
pyo3::Python::with_gil(|py| {
    let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap().readonly();
    let arr = arr.to_dyn().readonly();
    assert!(arr.get([1, 2].as_ref()).is_none());
});

pub fn iter(self) -> PyResult<NpySingleIter<'py, T, Readonly>>[src]

Iterates all elements of this array. See NpySingleIter for more.

Methods from Deref<Target = PyArray<T, D>>

pub fn as_array_ptr(&self) -> *mut PyArrayObject[src]

Gets a raw PyArrayObject pointer.

pub fn dtype(&self) -> &PyArrayDescr[src]

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_eq!(dtype.get_datatype().unwrap(), numpy::DataType::Int32);
});

pub fn readonly(&self) -> PyReadonlyArray<'_, T, D>[src]

Returns a temporally unwriteable reference of the array.

pub fn is_contiguous(&self) -> bool[src]

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))[::2, 4]", Some(locals), None)
        .unwrap()
        .downcast()
        .unwrap();
    assert!(!not_contiguous.is_contiguous());
});

pub fn is_fortran_contiguous(&self) -> bool[src]

Returns true if the internal data of the array is Fortran-style contiguous.

pub fn is_c_contiguous(&self) -> bool[src]

Returns true if the internal data of the array is C-style contiguous.

pub fn to_owned(&self) -> Py<Self>[src]

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]);
});

pub fn ndim(&self) -> usize[src]

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>::new(py, [4, 5, 6], false);
    assert_eq!(arr.ndim(), 3);
});

pub fn strides(&self) -> &[isize][src]

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>::new(py, [4, 5, 6], false);
    assert_eq!(arr.strides(), &[240, 48, 8]);
});

pub fn shape(&self) -> &[usize][src]

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>::new(py, [4, 5, 6], false);
    assert_eq!(arr.shape(), &[4, 5, 6]);
});

pub fn len(&self) -> usize[src]

Calcurates the total number of elements in the array.

pub fn is_empty(&self) -> bool[src]

pub fn dims(&self) -> D[src]

Same as shape, but returns D

pub unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>[src]

Returns the immutable view of the internal data of PyArray as slice.

Please consider the use of safe alternatives (PyReadonlyArray::as_slice , as_cell_slice or to_vec) instead of this.

Safety

If the internal array is not readonly and can be mutated from Python code, holding the slice might cause undefined behavior.

pub fn as_cell_slice(&self) -> Result<&[Cell<T>], NotContiguousError>[src]

Returns the view of the internal data of PyArray as &[Cell<T>].

pub unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>[src]

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.

In such case, please consider the use of as_cell_slice,

pub unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>[src]

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.

pub unsafe fn uget<Idx>(&self, index: Idx) -> &T where
    Idx: NpyIndex<Dim = D>, 
[src]

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.

Passing an invalid index can cause undefined behavior(mostly SIGSEGV).

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);
});

pub unsafe fn uget_mut<Idx>(&self, index: Idx) -> &mut T where
    Idx: NpyIndex<Dim = D>, 
[src]

Same as uget, but returns &mut T.

pub fn to_dyn(&self) -> &PyArray<T, IxDyn>[src]

Get dynamic dimensioned array from fixed dimension array.

pub fn get_owned(&self, index: impl NpyIndex<Dim = D>) -> Option<T>[src]

Get the copy of the specified element in the array.

See NpyIndex for what types you can use as index.

Example

use numpy::PyArray;
pyo3::Python::with_gil(|py| {
    let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
    assert_eq!(arr.get_owned([1, 0, 3]), Some(11));
});

pub fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>[src]

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]);
});

pub unsafe fn as_array(&self) -> ArrayView<'_, T, D>[src]

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.

pub unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>[src]

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.

pub fn to_owned_array(&self) -> Array<T, D>[src]

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]]
    )
});

pub fn item(&self) -> T[src]

Get the element of zero-dimensional PyArray.

See inner for example.

pub fn resize(&self, new_elems: usize) -> PyResult<()>[src]

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);
});

pub fn iter<'py>(&'py self) -> PyResult<NpySingleIter<'py, T, ReadWrite>>[src]

Iterates all elements of this array. See NpySingleIter for more.

pub fn copy_to<U: Element>(&self, other: &PyArray<U, D>) -> PyResult<()>[src]

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 = 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]);
});

pub fn cast<'py, U: Element>(
    &'py self,
    is_fortran: bool
) -> PyResult<&'py PyArray<U, D>>
[src]

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]);
});

pub fn reshape<'py, ID, D2>(
    &'py self,
    dims: ID
) -> PyResult<&'py PyArray<T, D2>> where
    ID: IntoDimension<Dim = D2>,
    D2: Dimension
[src]

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());
});

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
[src]

Same as reshape, but you can change the order of returned matrix.

Methods from Deref<Target = PyAny>

pub fn downcast<T>(&self) -> Result<&T, PyDowncastError<'_>> where
    T: for<'py> PyTryFrom<'py>, 
[src]

Convert this PyAny to a concrete Python type.

pub fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> where
    N: ToPyObject
[src]

Determines whether this object has the given attribute.

This is equivalent to the Python expression hasattr(self, attr_name).

pub fn getattr<N>(&self, attr_name: N) -> Result<&PyAny, PyErr> where
    N: ToPyObject
[src]

Retrieves an attribute value.

This is equivalent to the Python expression self.attr_name.

pub fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> where
    V: ToBorrowedObject,
    N: ToBorrowedObject
[src]

Sets an attribute value.

This is equivalent to the Python expression self.attr_name = value.

pub fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> where
    N: ToPyObject
[src]

Deletes an attribute.

This is equivalent to the Python expression del self.attr_name.

pub fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> where
    O: ToPyObject
[src]

Compares two Python objects.

This is equivalent to:

if self == other:
    return Equal
elif a < b:
    return Less
elif a > b:
    return Greater
else:
    raise TypeError("PyAny::compare(): All comparisons returned false")

pub fn rich_compare<O>(
    &self,
    other: O,
    compare_op: CompareOp
) -> Result<&PyAny, PyErr> where
    O: ToPyObject
[src]

Compares two Python objects.

Depending on the value of compare_op, this is equivalent to one of the following Python expressions:

  • CompareOp::Eq: self == other
  • CompareOp::Ne: self != other
  • CompareOp::Lt: self < other
  • CompareOp::Le: self <= other
  • CompareOp::Gt: self > other
  • CompareOp::Ge: self >= other

pub fn is_callable(&self) -> bool[src]

Determines whether this object is callable.

pub fn call(
    &self,
    args: impl IntoPy<Py<PyTuple>>,
    kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
[src]

Calls the object.

This is equivalent to the Python expression self(*args, **kwargs).

pub fn call0(&self) -> Result<&PyAny, PyErr>[src]

Calls the object without arguments.

This is equivalent to the Python expression self().

pub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> Result<&PyAny, PyErr>[src]

Calls the object with only positional arguments.

This is equivalent to the Python expression self(*args).

pub fn call_method(
    &self,
    name: &str,
    args: impl IntoPy<Py<PyTuple>>,
    kwargs: Option<&PyDict>
) -> Result<&PyAny, PyErr>
[src]

Calls a method on the object.

This is equivalent to the Python expression self.name(*args, **kwargs).

Example

use pyo3::types::IntoPyDict;

let gil = Python::acquire_gil();
let py = gil.python();
let list = vec![3, 6, 5, 4, 7].to_object(py);
let dict = vec![("reverse", true)].into_py_dict(py);
list.call_method(py, "sort", (), Some(dict)).unwrap();
assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]);

let new_element = 1.to_object(py);
list.call_method(py, "append", (new_element,), None).unwrap();
assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3, 1]);

pub fn call_method0(&self, name: &str) -> Result<&PyAny, PyErr>[src]

Calls a method on the object without arguments.

This is equivalent to the Python expression self.name().

pub fn call_method1(
    &self,
    name: &str,
    args: impl IntoPy<Py<PyTuple>>
) -> Result<&PyAny, PyErr>
[src]

Calls a method on the object with only positional arguments.

This is equivalent to the Python expression self.name(*args).

pub fn is_true(&self) -> Result<bool, PyErr>[src]

Returns whether the object is considered to be true.

This is equivalent to the Python expression bool(self).

pub fn is_none(&self) -> bool[src]

Returns whether the object is considered to be None.

This is equivalent to the Python expression self is None.

pub fn is_empty(&self) -> Result<bool, PyErr>[src]

Returns true if the sequence or mapping has a length of 0.

This is equivalent to the Python expression len(self) == 0.

pub fn get_item<K>(&self, key: K) -> Result<&PyAny, PyErr> where
    K: ToBorrowedObject
[src]

Gets an item from the collection.

This is equivalent to the Python expression self[key].

pub fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> where
    K: ToBorrowedObject,
    V: ToBorrowedObject
[src]

Sets a collection item value.

This is equivalent to the Python expression self[key] = value.

pub fn del_item<K>(&self, key: K) -> Result<(), PyErr> where
    K: ToBorrowedObject
[src]

Deletes an item from the collection.

This is equivalent to the Python expression del self[key].

pub fn iter(&self) -> Result<&PyIterator, PyErr>[src]

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.

pub fn get_type(&self) -> &PyType[src]

Returns the Python type object for this object’s type.

pub fn get_type_ptr(&self) -> *mut PyTypeObject[src]

Returns the Python type pointer for this object.

pub fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError<'a>> where
    D: PyTryFrom<'a>, 
[src]

Casts the PyObject to a concrete Python object type.

This can cast only to native Python types, not types implemented in Rust.

pub fn extract<'a, D>(&'a self) -> Result<D, PyErr> where
    D: FromPyObject<'a>, 
[src]

Extracts some type from the Python object.

This is a wrapper function around FromPyObject::extract().

pub fn get_refcnt(&self) -> isize[src]

Returns the reference count for the Python object.

pub fn repr(&self) -> Result<&PyString, PyErr>[src]

Computes the “repr” representation of self.

This is equivalent to the Python expression repr(self).

pub fn str(&self) -> Result<&PyString, PyErr>[src]

Computes the “str” representation of self.

This is equivalent to the Python expression str(self).

pub fn hash(&self) -> Result<isize, PyErr>[src]

Retrieves the hash code of self.

This is equivalent to the Python expression hash(self).

pub fn len(&self) -> Result<usize, PyErr>[src]

Returns the length of the sequence or mapping.

This is equivalent to the Python expression len(self).

pub fn dir(&self) -> &PyList[src]

Returns the list of attributes of this object.

This is equivalent to the Python expression dir(self).

pub fn is_instance<T>(&self) -> Result<bool, PyErr> where
    T: PyTypeObject
[src]

Checks whether this object is an instance of type T.

This is equivalent to the Python expression isinstance(self, T).

Trait Implementations

impl<'py, T, D> AsRef<PyArray<T, D>> for PyReadonlyArray<'py, T, D>[src]

impl<'py, T, D> Deref for PyReadonlyArray<'py, T, D>[src]

type Target = PyArray<T, D>

The resulting type after dereferencing.

impl<'py, T, D> Drop for PyReadonlyArray<'py, T, D>[src]

impl<'py, T, D> From<&'py PyArray<T, D>> for PyReadonlyArray<'py, T, D>[src]

impl<'py, T: Element, D: Dimension> FromPyObject<'py> for PyReadonlyArray<'py, T, D>[src]

impl<'py, T, D> IntoPy<Py<PyAny>> for PyReadonlyArray<'py, T, D>[src]

Auto Trait Implementations

impl<'py, T, D> !RefUnwindSafe for PyReadonlyArray<'py, T, D>

impl<'py, T, D> !Send for PyReadonlyArray<'py, T, D>

impl<'py, T, D> !Sync for PyReadonlyArray<'py, T, D>

impl<'py, T, D> Unpin for PyReadonlyArray<'py, T, D>

impl<'py, T, D> !UnwindSafe for PyReadonlyArray<'py, T, D>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.