Struct cpython::PySharedRefCell[][src]

pub struct PySharedRefCell<T: ?Sized> { /* fields omitted */ }

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();
            RefCell::new(unsafe {, |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(|v| v.to_py_object(py)))

    def __iter__(&self) -> PyResult<Self> {

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.


impl<T> PySharedRefCell<T>[src]

pub fn new(value: T) -> PySharedRefCell<T>[src]

Creates a new PySharedRefCell containing value.

Trait Implementations

impl<T: Debug + ?Sized> Debug for PySharedRefCell<T>[src]

Auto Trait Implementations

impl<T> !RefUnwindSafe for PySharedRefCell<T>[src]

impl<T: ?Sized> Send for PySharedRefCell<T> where
    T: Send

impl<T> !Sync for PySharedRefCell<T>[src]

impl<T: ?Sized> Unpin for PySharedRefCell<T> where
    T: Unpin

impl<T: ?Sized> UnwindSafe for PySharedRefCell<T> where
    T: UnwindSafe

Blanket Implementations

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

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

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

impl<T> From<T> for T[src]

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

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

type Error = Infallible

The type returned in the event of a conversion error.

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

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

The type returned in the event of a conversion error.