Skip to main content

PyBorrowedUnbound

Struct PyBorrowedUnbound 

Source
#[repr(transparent)]
pub(crate) struct PyBorrowedUnbound<'a, T>(NonNull<PyObject>, PhantomData<&'a Py<T>>);
Expand description

Variant of Borrowed which doesn’t have the attachment lifetime 'py and therefore can be used in contexts where the Python interpreter is not attached, such as during GC traversal.

This is intended to be a private type for now as it’s unlikely to have much use outside of PyO3 internals. It also has a horrible name. It comes in useful as a better alternative to NonNull<ffi::PyObject> because it carries the lifetime of validity plus type information.

Tuple Fields§

§0: NonNull<PyObject>§1: PhantomData<&'a Py<T>>

Implementations§

Source§

impl<'a> PyBorrowedUnbound<'a, PyAny>

Source

pub(crate) unsafe fn from_non_null(ptr: NonNull<PyObject>) -> Self

§Safety

ptr must be a valid pointer to a Python object. The caller is responsible for scoping the unbound lifetime 'a.

Source§

impl<'a, T> PyBorrowedUnbound<'a, T>

Source

pub(crate) unsafe fn cast_unchecked<U>(self) -> PyBorrowedUnbound<'a, U>

§Safety

Callers must ensure that the type is valid or risk type confusion.

Methods from Deref<Target = 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 as_any(&self) -> &Py<PyAny>

Helper to cast to Py<PyAny>.

Source

pub(crate) fn as_non_null(&self) -> NonNull<PyObject>

Source

pub fn borrow<'py>(&'py self, py: Python<'py>) -> 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.

Equivalent to self.bind(py).borrow() - see Bound::borrow.

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

Python::attach(|py| -> PyResult<()> {
    let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?;
    let inner: &u8 = &foo.borrow(py).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<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>
where T: PyClass<Frozen = False>,

Mutably borrows the value T.

This borrow lasts while the returned PyRefMut exists.

Equivalent to self.bind(py).borrow_mut() - see Bound::borrow_mut.

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

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

    assert_eq!(foo.borrow(py).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<'py>( &'py self, py: Python<'py>, ) -> 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.

Equivalent to self.bind(py).try_borrow() - see Bound::try_borrow.

Source

pub fn try_borrow_mut<'py>( &'py self, py: Python<'py>, ) -> 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.

Equivalent to self.bind(py).try_borrow_mut() - see Bound::try_borrow_mut.

Source

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

Provide an immutable borrow of the value T.

This is available if the class is frozen and Sync, and does not require attaching to the Python interpreter.

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

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

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

    Py::new(py, counter).unwrap()
});

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

pub(crate) fn get_class_object(&self) -> &<T as PyClassImpl>::Layout

Get a view on the underlying PyClass contents.

Source

pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T>

Attaches this Py to the given Python context, allowing access to further Python APIs.

Source

pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T>

Same as bind but produces a Borrowed<T> instead of a Bound<T>.

Source

pub fn is<U: AsRef<Py<PyAny>>>(&self, o: U) -> bool

Returns whether self and other point to the same object. To compare the equality of two objects (the == operator), use eq.

This is equivalent to the Python expression self is other.

Source

pub fn get_refcnt(&self, py: Python<'_>) -> isize

👎Deprecated since 0.29.0:

use pyo3::ffi::Py_REFCNT(obj.as_ptr()) instead

Gets the reference count of the ffi::PyObject pointer.

Source

pub(crate) fn _get_refcnt(&self, _py: Python<'_>) -> isize

Source

pub fn clone_ref(&self, _py: Python<'_>) -> Py<T>

Makes a clone of self.

This creates another pointer to the same object, increasing its reference count.

You should prefer using this method over Clone.

§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;

Python::attach(|py| {
    let first: Py<PyDict> = PyDict::new(py).unbind();
    let second = Py::clone_ref(&first, py);

    // Both point to the same object
    assert!(first.is(&second));
});
Source

pub fn is_none(&self, py: Python<'_>) -> bool

Returns whether the object is considered to be None.

This is equivalent to the Python expression self is None.

Source

pub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool>

Returns whether the object is considered to be true.

This applies truth value testing equivalent to the Python expression bool(self).

Source

pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> Result<D, D::Error>
where D: FromPyObject<'a, 'py>,

Extracts some type from the Python object.

This is a wrapper function around FromPyObject::extract().

Source

pub fn getattr<'py, N>( &self, py: Python<'py>, attr_name: N, ) -> PyResult<Py<PyAny>>
where N: IntoPyObject<'py, Target = PyString>,

Retrieves an attribute value.

This is equivalent to the Python expression self.attr_name.

If calling this method becomes performance-critical, the intern! macro can be used to intern attr_name, thereby avoiding repeated temporary allocations of Python strings.

§Example: intern!ing the attribute name
#[pyfunction]
fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<Py<PyAny>> {
    sys.getattr(py, intern!(py, "version"))
}
Source

pub fn setattr<'py, N, V>( &self, py: Python<'py>, attr_name: N, value: V, ) -> PyResult<()>
where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>,

Sets an attribute value.

This is equivalent to the Python expression self.attr_name = value.

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern attr_name.

§Example: intern!ing the attribute name
#[pyfunction]
fn set_answer(ob: Py<PyAny>, py: Python<'_>) -> PyResult<()> {
    ob.setattr(py, intern!(py, "answer"), 42)
}
Source

pub fn call<'py, A>( &self, py: Python<'py>, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Py<PyAny>>
where A: PyCallArgs<'py>,

Calls the object.

This is equivalent to the Python expression self(*args, **kwargs).

Source

pub fn call1<'py, A>(&self, py: Python<'py>, args: A) -> PyResult<Py<PyAny>>
where A: PyCallArgs<'py>,

Calls the object with only positional arguments.

This is equivalent to the Python expression self(*args).

Source

pub fn call0(&self, py: Python<'_>) -> PyResult<Py<PyAny>>

Calls the object without arguments.

This is equivalent to the Python expression self().

Source

pub fn call_method<'py, N, A>( &self, py: Python<'py>, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Py<PyAny>>
where N: IntoPyObject<'py, Target = PyString>, A: PyCallArgs<'py>,

Calls a method on the object.

This is equivalent to the Python expression self.name(*args, **kwargs).

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Source

pub fn call_method1<'py, N, A>( &self, py: Python<'py>, name: N, args: A, ) -> PyResult<Py<PyAny>>
where N: IntoPyObject<'py, Target = PyString>, A: PyCallArgs<'py>,

Calls a method on the object with only positional arguments.

This is equivalent to the Python expression self.name(*args).

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Source

pub fn call_method0<'py, N>( &self, py: Python<'py>, name: N, ) -> PyResult<Py<PyAny>>
where N: IntoPyObject<'py, Target = PyString>,

Calls a method on the object with no arguments.

This is equivalent to the Python expression self.name().

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Source

pub fn cast_bound<'py, U>( &self, py: Python<'py>, ) -> Result<&Bound<'py, U>, CastError<'_, 'py>>
where U: PyTypeCheck,

Cast this Py<T> to a concrete Python type or pyclass.

Note that you can often avoid casting yourself by just specifying the desired type in function or method signatures. However, manual casting is sometimes necessary.

For extracting a Rust-only type, see Py::extract.

§Example: Casting to a specific Python object
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};

Python::attach(|py| {
    let any = PyDict::new(py).into_any().unbind();

    assert!(any.cast_bound::<PyDict>(py).is_ok());
    assert!(any.cast_bound::<PyList>(py).is_err());
});
§Example: Getting a reference to a pyclass

This is useful if you want to mutate a Py<PyAny> that might actually be a pyclass.

use pyo3::prelude::*;

#[pyclass]
struct Class {
    i: i32,
}

Python::attach(|py| {
    let class = Py::new(py, Class { i: 0 })?.into_any();

    let class_bound = class.cast_bound::<Class>(py)?;

    class_bound.borrow_mut().i += 1;

    // Alternatively you can get a `PyRefMut` directly
    let class_ref: PyRefMut<'_, Class> = class.extract(py)?;
    assert_eq!(class_ref.i, 1);
    Ok(())
})
Source

pub unsafe fn cast_bound_unchecked<'py, U>( &self, py: Python<'py>, ) -> &Bound<'py, U>

Casts the Py<T> to a concrete Python object type without checking validity.

§Safety

Callers must ensure that the type is valid or risk type confusion.

Trait Implementations§

Source§

impl<'a, T> Clone for PyBorrowedUnbound<'a, T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a, T> Copy for PyBorrowedUnbound<'a, T>

Source§

impl<'a, T> Deref for PyBorrowedUnbound<'a, T>

Source§

type Target = Py<T>

The resulting type after dereferencing.
Source§

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

Dereferences the value.

Auto Trait Implementations§

§

impl<'a, T> !Send for PyBorrowedUnbound<'a, T>

§

impl<'a, T> !Sync for PyBorrowedUnbound<'a, T>

§

impl<'a, T> Freeze for PyBorrowedUnbound<'a, T>
where PhantomData<&'a Py<T>>: Freeze,

§

impl<'a, T> RefUnwindSafe for PyBorrowedUnbound<'a, T>
where PhantomData<&'a Py<T>>: RefUnwindSafe,

§

impl<'a, T> Unpin for PyBorrowedUnbound<'a, T>
where PhantomData<&'a Py<T>>: Unpin,

§

impl<'a, T> UnsafeUnpin for PyBorrowedUnbound<'a, T>
where PhantomData<&'a Py<T>>: UnsafeUnpin,

§

impl<'a, T> UnwindSafe for PyBorrowedUnbound<'a, T>
where PhantomData<&'a Py<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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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> SizeHint for T
where T: ?Sized,

Source§

default fn lower_bound(&self) -> usize

🔬This is a nightly-only experimental API. (core_io_internals)
Returns a lower bound on the number of elements this container-like item contains. For example, an array [u8; 12] could return any value between 0 and 12 inclusively as a correct implementation. Read more
Source§

default fn upper_bound(&self) -> Option<usize>

🔬This is a nightly-only experimental API. (core_io_internals)
Returns an upper bound on the number of elements this container-like item contains if it can be determined, otherwise None. Read more
Source§

final fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (core_io_internals)
Returns an estimate for the number of elements this container like type contains. Read more
Source§

impl<T> SizedTypeProperties for T

Source§

#[doc(hidden)]
const SIZE: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const ALIGN: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const ALIGNMENT: Alignment = _

🔬This is a nightly-only experimental API. (ptr_alignment_type)
Source§

#[doc(hidden)]
const IS_ZST: bool = _

🔬This is a nightly-only experimental API. (sized_type_properties)
true if this type requires no storage. false if its size is greater than zero. Read more
Source§

#[doc(hidden)]
const LAYOUT: Layout = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const MAX_SLICE_LEN: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
The largest safe length for a [Self]. Read more
Source§

impl<T> SomeWrap<T> for T

Source§

fn wrap(self) -> Option<T>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here