pub struct PyReadonlyArray<'py, T, D> { /* private fields */ }
Expand description

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

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, dtype='int32')[::2]", Some(locals), None)
        .unwrap()
        .downcast()
        .unwrap();
    assert!(not_contiguous.readonly().as_slice().is_err());
});

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

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

The wrappers of the array iterator API are deprecated, please use ndarray’s ArrayBase::iter instead.

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

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

Gets a raw PyArrayObject pointer.

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

Returns a temporally unwriteable reference of the array.

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

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

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

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

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

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

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

Calcurates the total number of elements in the array.

Same as shape, but returns D

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.

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.

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.

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

Same as uget, but returns &mut T.

Safety

Passing an invalid index is undefined behavior. The element must also have been initialized. The element must also not be accessed by Python code.

Same as uget, but returns *mut T.

Safety

Passing an invalid index is undefined behavior.

Get dynamic dimensioned array from fixed dimension array.

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

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

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.

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.

Returns the internal array as RawArrayView enabling element access via raw pointers

Returns the internal array as RawArrayViewMut enabling element access via raw pointers

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

Get the element of zero-dimensional PyArray.

See inner for example.

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);
});
👎 Deprecated:

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.

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

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

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

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

Methods from Deref<Target = PyAny>

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

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.

Determines whether this object has the given attribute.

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

Retrieves an attribute value.

This is equivalent to the Python expression self.attr_name.

Sets an attribute value.

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

Deletes an attribute.

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

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

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_opPython expression
CompareOp::Eqself == other
CompareOp::Neself != other
CompareOp::Ltself < other
CompareOp::Leself <= other
CompareOp::Gtself > other
CompareOp::Geself >= 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(())
})?;

Tests whether this object is less than another.

This is equivalent to the Python expression self < other.

Tests whether this object is less than or equal to another.

This is equivalent to the Python expression self <= other.

Tests whether this object is equal to another.

This is equivalent to the Python expression self == other.

Tests whether this object is not equal to another.

This is equivalent to the Python expression self != other.

Tests whether this object is greater than another.

This is equivalent to the Python expression self > other.

Tests whether this object is greater than or equal to another.

This is equivalent to the Python expression self >= other.

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.

Calls the object.

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

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().

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

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]

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

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]

Returns whether the object is considered to be true.

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

Returns whether the object is considered to be None.

This is equivalent to the Python expression self is None.

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

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

Gets an item from the collection.

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

Sets a collection item value.

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

Deletes an item from the collection.

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

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.

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

Returns the Python type pointer for this object.

Casts the PyObject to a concrete Python object type.

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

Extracts some type from the Python object.

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

Returns the reference count for the Python object.

Computes the “repr” representation of self.

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

Computes the “str” representation of self.

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

Retrieves the hash code of self.

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

Returns the length of the sequence or mapping.

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

Returns the list of attributes of this object.

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

Checks whether this object is an instance of type typ.

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

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.

Determines if self contains value.

This is equivalent to the Python expression value in self.

Returns a GIL marker constrained to the lifetime of this type.

Trait Implementations

Performs the conversion.

The resulting type after dereferencing.

Dereferences the value.

Executes the destructor for this type. Read more

Performs the conversion.

Extracts Self from the source PyObject.

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.