Struct PyArrayLike

Source
pub struct PyArrayLike<'py, T, D, C = TypeMustMatch>(/* private fields */)
where
    T: Element,
    D: Dimension,
    C: Coerce;
Expand description

Receiver for arrays or array-like types.

When building API using NumPy in Python, it is common for functions to additionally accept any array-like type such as list[float] as arguments. PyArrayLike enables the same pattern in Rust extensions, i.e. by taking this type as the argument of a #[pyfunction], one will always get access to a PyReadonlyArray that will either reference to the NumPy array originally passed into the function or a temporary one created by converting the input type into a NumPy array.

Depending on whether TypeMustMatch or AllowTypeChange is used for the C type parameter, the element type must either match the specific type T exactly or will be cast to it by NumPy’s asarray.

§Example

PyArrayLike1<'py, T, TypeMustMatch> will enable you to receive both NumPy arrays and sequences

use pyo3::py_run;
use numpy::{get_array_module, PyArrayLike1, TypeMustMatch};

#[pyfunction]
fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, f64, TypeMustMatch>) -> f64 {
    array.as_array().sum()
}

Python::with_gil(|py| {
    let np = get_array_module(py).unwrap();
    let sum_up = wrap_pyfunction!(sum_up)(py).unwrap();

    py_run!(py, np sum_up, r"assert sum_up(np.array([1., 2., 3.])) == 6.");
    py_run!(py, np sum_up, r"assert sum_up((1., 2., 3.)) == 6.");
});

but it will not cast the element type if that is required

use pyo3::prelude::*;
use pyo3::py_run;
use numpy::{get_array_module, PyArrayLike1, TypeMustMatch};

#[pyfunction]
fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, i32, TypeMustMatch>) -> i32 {
    array.as_array().sum()
}

Python::with_gil(|py| {
    let np = get_array_module(py).unwrap();
    let sum_up = wrap_pyfunction!(sum_up)(py).unwrap();

    py_run!(py, np sum_up, r"assert sum_up((1., 2., 3.)) == 6");
});

whereas PyArrayLike1<'py, T, AllowTypeChange> will do even at the cost loosing precision

use pyo3::prelude::*;
use pyo3::py_run;
use numpy::{get_array_module, AllowTypeChange, PyArrayLike1};

#[pyfunction]
fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, i32, AllowTypeChange>) -> i32 {
    array.as_array().sum()
}

Python::with_gil(|py| {
    let np = get_array_module(py).unwrap();
    let sum_up = wrap_pyfunction!(sum_up)(py).unwrap();

    py_run!(py, np sum_up, r"assert sum_up((1.5, 2.5)) == 3");
});

Methods from Deref<Target = PyReadonlyArray<'py, T, D>>§

Source

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

Provides an immutable array view of the interior of the NumPy array.

Source

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

Provide an immutable slice view of the interior of the NumPy array if it is contiguous.

Source

pub fn get<I>(&self, index: I) -> Option<&T>
where I: NpyIndex<Dim = D>,

Provide an immutable reference to an element of the NumPy array if the index is within bounds.

Methods from Deref<Target = Bound<'py, PyArray<T, D>>>§

Source

pub fn borrow(&self) -> PyRef<'py, T>

Immutably borrows the value T.

This borrow lasts while the returned PyRef exists. Multiple immutable borrows can be taken out at the same time.

For frozen classes, the simpler get is available.

§Examples
#[pyclass]
struct Foo {
    inner: u8,
}

Python::with_gil(|py| -> PyResult<()> {
    let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
    let inner: &u8 = &foo.borrow().inner;

    assert_eq!(*inner, 73);
    Ok(())
})?;
§Panics

Panics if the value is currently mutably borrowed. For a non-panicking variant, use try_borrow.

Source

pub fn borrow_mut(&self) -> PyRefMut<'py, T>
where T: PyClass<Frozen = False>,

Mutably borrows the value T.

This borrow lasts while the returned PyRefMut exists.

§Examples
#[pyclass]
struct Foo {
    inner: u8,
}

Python::with_gil(|py| -> PyResult<()> {
    let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
    foo.borrow_mut().inner = 35;

    assert_eq!(foo.borrow().inner, 35);
    Ok(())
})?;
§Panics

Panics if the value is currently borrowed. For a non-panicking variant, use try_borrow_mut.

Source

pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError>

Attempts to immutably borrow the value T, returning an error if the value is currently mutably borrowed.

The borrow lasts while the returned PyRef exists.

This is the non-panicking variant of borrow.

For frozen classes, the simpler get is available.

Source

pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
where T: PyClass<Frozen = False>,

Attempts to mutably borrow the value T, returning an error if the value is currently borrowed.

The borrow lasts while the returned PyRefMut exists.

This is the non-panicking variant of borrow_mut.

Source

pub fn get(&self) -> &T
where T: PyClass<Frozen = True> + Sync,

Provide an immutable borrow of the value T without acquiring the GIL.

This is available if the class is frozen and Sync.

§Examples
use std::sync::atomic::{AtomicUsize, Ordering};

#[pyclass(frozen)]
struct FrozenCounter {
    value: AtomicUsize,
}

Python::with_gil(|py| {
    let counter = FrozenCounter { value: AtomicUsize::new(0) };

    let py_counter = Bound::new(py, counter).unwrap();

    py_counter.get().value.fetch_add(1, Ordering::Relaxed);
});
Source

pub fn as_super(&self) -> &Bound<'py, <T as PyClassImpl>::BaseType>

Upcast this Bound<PyClass> to its base type by reference.

If this type defined an explicit base class in its pyclass declaration (e.g. #[pyclass(extends = BaseType)]), the returned type will be &Bound<BaseType>. If an explicit base class was not declared, the return value will be &Bound<PyAny> (making this method equivalent to as_any).

This method is particularly useful for calling methods defined in an extension trait that has been implemented for Bound<BaseType>.

See also the into_super method to upcast by value, and the PyRef::as_super/PyRefMut::as_super methods for upcasting a pyclass that has already been borrowed.

§Example: Calling a method defined on the Bound base type
use pyo3::prelude::*;

#[pyclass(subclass)]
struct BaseClass;

trait MyClassMethods<'py> {
    fn pyrepr(&self) -> PyResult<String>;
}
impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> {
    fn pyrepr(&self) -> PyResult<String> {
        self.call_method0("__repr__")?.extract()
    }
}

#[pyclass(extends = BaseClass)]
struct SubClass;

Python::with_gil(|py| {
    let obj = Bound::new(py, (SubClass, BaseClass)).unwrap();
    assert!(obj.as_super().pyrepr().is_ok());
})
Source

pub fn py(&self) -> Python<'py>

Returns the GIL token associated with this object.

Source

pub fn as_ptr(&self) -> *mut PyObject

Returns the raw FFI pointer represented by self.

§Safety

Callers are responsible for ensuring that the pointer does not outlive self.

The reference is borrowed; callers should not decrease the reference count when they are finished with the pointer.

Source

pub fn as_any(&self) -> &Bound<'py, PyAny>

Helper to cast to Bound<'py, PyAny>.

Source

pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T>

Casts this Bound<T> to a Borrowed<T> smart pointer.

Source

pub fn as_unbound(&self) -> &Py<T>

Removes the connection for this Bound<T> from the GIL, allowing it to cross thread boundaries, without transferring ownership.

Trait Implementations§

Source§

impl<'py, T, D, C> Debug for PyArrayLike<'py, T, D, C>
where T: Element + Debug, D: Dimension + Debug, C: Coerce + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'py, T, D, C> Deref for PyArrayLike<'py, T, D, C>
where T: Element, D: Dimension, C: Coerce,

Source§

type Target = PyReadonlyArray<'py, T, D>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<'py, T, D, C> FromPyObject<'py> for PyArrayLike<'py, T, D, C>
where T: Element + 'py, D: Dimension + 'py, C: Coerce, Vec<T>: FromPyObject<'py>,

Source§

fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self>

Extracts Self from the bound smart pointer obj. Read more

Auto Trait Implementations§

§

impl<'py, T, D, C> Freeze for PyArrayLike<'py, T, D, C>

§

impl<'py, T, D, C = TypeMustMatch> !RefUnwindSafe for PyArrayLike<'py, T, D, C>

§

impl<'py, T, D, C = TypeMustMatch> !Send for PyArrayLike<'py, T, D, C>

§

impl<'py, T, D, C = TypeMustMatch> !Sync for PyArrayLike<'py, T, D, C>

§

impl<'py, T, D, C> Unpin for PyArrayLike<'py, T, D, C>
where C: Unpin, T: Unpin, D: Unpin,

§

impl<'py, T, D, C> UnwindSafe for PyArrayLike<'py, T, D, C>
where C: UnwindSafe, T: UnwindSafe, D: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<'py, T> FromPyObjectBound<'_, 'py> for T
where T: FromPyObject<'py>,

Source§

fn from_py_object_bound(ob: Borrowed<'_, 'py, PyAny>) -> Result<T, PyErr>

Extracts Self from the bound smart pointer obj. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V