pyo3::pycell

Struct PyRef

Source
pub struct PyRef<'p, T: PyClass> { /* private fields */ }
Expand description

A wrapper type for an immutably borrowed value from a [Bound<'py, T>].

See the Bound documentation for more information.

§Examples

You can use PyRef as an alternative to a &self receiver when

  • you need to access the pointer of the Bound, or
  • you want to get a super class.
#[pyclass(subclass)]
struct Parent {
    basename: &'static str,
}

#[pyclass(extends=Parent)]
struct Child {
    name: &'static str,
 }

#[pymethods]
impl Child {
    #[new]
    fn new() -> (Self, Parent) {
        (Child { name: "Caterpillar" }, Parent { basename: "Butterfly" })
    }

    fn format(slf: PyRef<'_, Self>) -> String {
        // We can get *mut ffi::PyObject from PyRef
        let refcnt = unsafe { pyo3::ffi::Py_REFCNT(slf.as_ptr()) };
        // We can get &Self::BaseType by as_ref
        let basename = slf.as_ref().basename;
        format!("{}(base: {}, cnt: {})", slf.name, basename, refcnt)
    }
}

See the module-level documentation for more information.

Implementations§

Source§

impl<'p, T: PyClass> PyRef<'p, T>

Source

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

Returns a Python token that is bound to the lifetime of the PyRef.

Source§

impl<'py, T: PyClass> PyRef<'py, T>

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 into_ptr(self) -> *mut PyObject

Returns an owned raw FFI pointer represented by self.

§Safety

The reference is owned; when finished the caller should either transfer ownership of the pointer or decrease the reference count (e.g. with pyo3::ffi::Py_DecRef).

Source§

impl<'p, T, U> PyRef<'p, T>
where T: PyClass<BaseType = U>, U: PyClass,

Source

pub fn into_super(self) -> PyRef<'p, U>

Gets a PyRef<T::BaseType>.

While as_ref() returns a reference of type &T::BaseType, this cannot be used to get the base of T::BaseType.

But with the help of this method, you can get hold of instances of the super-superclass when needed.

§Examples
#[pyclass(subclass)]
struct Base1 {
    name1: &'static str,
}

#[pyclass(extends=Base1, subclass)]
struct Base2 {
    name2: &'static str,
}

#[pyclass(extends=Base2)]
struct Sub {
    name3: &'static str,
}

#[pymethods]
impl Sub {
    #[new]
    fn new() -> PyClassInitializer<Self> {
        PyClassInitializer::from(Base1 { name1: "base1" })
            .add_subclass(Base2 { name2: "base2" })
            .add_subclass(Self { name3: "sub" })
    }
    fn name(slf: PyRef<'_, Self>) -> String {
        let subname = slf.name3;
        let super_ = slf.into_super();
        format!("{} {} {}", super_.as_ref().name1, super_.name2, subname)
    }
}
Source

pub fn as_super(&self) -> &PyRef<'p, U>

Borrows a shared reference to PyRef<T::BaseType>.

With the help of this method, you can access attributes and call methods on the superclass without consuming the PyRef<T>. This method can also be chained to access the super-superclass (and so on).

§Examples
#[pyclass(subclass)]
struct Base {
    base_name: &'static str,
}
#[pymethods]
impl Base {
    fn base_name_len(&self) -> usize {
        self.base_name.len()
    }
}

#[pyclass(extends=Base)]
struct Sub {
    sub_name: &'static str,
}

#[pymethods]
impl Sub {
    #[new]
    fn new() -> (Self, Base) {
        (Self { sub_name: "sub_name" }, Base { base_name: "base_name" })
    }
    fn sub_name_len(&self) -> usize {
        self.sub_name.len()
    }
    fn format_name_lengths(slf: PyRef<'_, Self>) -> String {
        format!("{} {}", slf.as_super().base_name_len(), slf.sub_name_len())
    }
}

Trait Implementations§

Source§

impl<'a, T: PyClass> AsPyPointer for PyRef<'a, T>

Source§

fn as_ptr(&self) -> *mut PyObject

Returns the underlying FFI pointer as a borrowed pointer.
Source§

impl<'p, T, U> AsRef<U> for PyRef<'p, T>
where T: PyClass<BaseType = U>, U: PyClass,

Source§

fn as_ref(&self) -> &T::BaseType

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: PyClass + Debug> Debug for PyRef<'_, T>

Source§

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

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

impl<'p, T: PyClass> Deref for PyRef<'p, T>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &T

Dereferences the value.
Source§

impl<'p, T: PyClass> Drop for PyRef<'p, T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a, T> From<PyRef<'a, T>> for Py<T>
where T: PyClass,

Source§

fn from(pyref: PyRef<'a, T>) -> Self

Converts to this type from the input type.
Source§

impl<'py, T> FromPyObject<'py> for PyRef<'py, T>
where T: PyClass,

Source§

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

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

impl<T: PyClass> IntoPy<Py<PyAny>> for &PyRef<'_, T>

Source§

fn into_py(self, py: Python<'_>) -> PyObject

Performs the conversion.
Source§

impl<T: PyClass> IntoPy<Py<PyAny>> for PyRef<'_, T>

Source§

fn into_py(self, py: Python<'_>) -> PyObject

Performs the conversion.

Auto Trait Implementations§

§

impl<'p, T> Freeze for PyRef<'p, T>

§

impl<'p, T> RefUnwindSafe for PyRef<'p, T>
where T: RefUnwindSafe,

§

impl<'p, T> !Send for PyRef<'p, T>

§

impl<'p, T> !Sync for PyRef<'p, T>

§

impl<'p, T> Unpin for PyRef<'p, T>
where T: Unpin,

§

impl<'p, T> UnwindSafe for PyRef<'p, T>
where T: 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.