pub struct PySharedRefCell<T: ?Sized> { /* private fields */ }
Expand description

A mutable memory location shareable immutably across Python objects.

This is a RefCell that can also be borrowed immutably by another Python object.

The primary use case is to implement a Python iterator over a Rust iterator. Since a Python object cannot hold a lifetime-bound object, Iter<'a, T> cannot be a data field of the Python iterator object. PySharedRef::leak_immutable() provides a way around this issue.

py_class!(pub class List |py| {
    @shared data rust_vec: Vec<i32>;

    def __iter__(&self) -> PyResult<ListIterator> {
        let leaked = self.rust_vec(py).leak_immutable();
        ListIterator::create_instance(
            py,
            RefCell::new(unsafe { leaked.map(py, |o| o.iter()) }),
        )
    }
});

py_class!(pub class ListIterator |py| {
    data rust_iter: RefCell<UnsafePyLeaked<Iter<'static, i32>>>;

    def __next__(&self) -> PyResult<Option<PyInt>> {
        let mut leaked = self.rust_iter(py).borrow_mut();
        let mut iter = unsafe { leaked.try_borrow_mut(py)? };
        Ok(iter.next().map(|v| v.to_py_object(py)))
    }

    def __iter__(&self) -> PyResult<Self> {
        Ok(self.clone_ref(py))
    }
});

The borrow rules are enforced dynamically in a similar manner to the Python iterator.

PySharedRefCell is merely a data struct to be stored in a Python object. Any further operation will be performed through PySharedRef, which is a lifetime-bound reference to the PySharedRefCell.

Implementations

Creates a new PySharedRefCell containing value.

Trait Implementations

Formats the value using the given formatter. Read more

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.