Struct pyo3::pycell::PyRef[][src]

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

A wrapper type for an immutably borrowed value from a PyCell<T>.

See the PyCell 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 PyCell, 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
        use pyo3::AsPyPointer;
        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

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

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

Trait Implementations

Retrieves the underlying FFI pointer (as a borrowed pointer).

Performs the conversion.

Formats the value using the given formatter. Read more

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.

The type returned in the event of a conversion error.

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

Performs the conversion.

Performs the conversion.

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.