#[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>
impl<'a> PyBorrowedUnbound<'a, PyAny>
Sourcepub(crate) unsafe fn from_non_null(ptr: NonNull<PyObject>) -> Self
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>
impl<'a, T> PyBorrowedUnbound<'a, T>
Sourcepub(crate) unsafe fn cast_unchecked<U>(self) -> PyBorrowedUnbound<'a, U>
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>>§
Sourcepub fn as_ptr(&self) -> *mut PyObject
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.
pub(crate) fn as_non_null(&self) -> NonNull<PyObject>
Sourcepub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T>
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.
Sourcepub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>
pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>
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.
Sourcepub fn try_borrow<'py>(
&'py self,
py: Python<'py>,
) -> Result<PyRef<'py, T>, PyBorrowError>
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.
Sourcepub fn try_borrow_mut<'py>(
&'py self,
py: Python<'py>,
) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
pub fn try_borrow_mut<'py>( &'py self, py: Python<'py>, ) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
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.
Sourcepub fn get(&self) -> &T
pub fn get(&self) -> &T
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);Sourcepub(crate) fn get_class_object(&self) -> &<T as PyClassImpl>::Layout
pub(crate) fn get_class_object(&self) -> &<T as PyClassImpl>::Layout
Get a view on the underlying PyClass contents.
Sourcepub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T>
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.
Sourcepub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T>
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>.
Sourcepub fn is<U: AsRef<Py<PyAny>>>(&self, o: U) -> bool
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.
Sourcepub fn get_refcnt(&self, py: Python<'_>) -> isize
👎Deprecated since 0.29.0: use pyo3::ffi::Py_REFCNT(obj.as_ptr()) instead
pub fn get_refcnt(&self, py: Python<'_>) -> isize
use pyo3::ffi::Py_REFCNT(obj.as_ptr()) instead
Gets the reference count of the ffi::PyObject pointer.
pub(crate) fn _get_refcnt(&self, _py: Python<'_>) -> isize
Sourcepub fn clone_ref(&self, _py: Python<'_>) -> Py<T>
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));
});Sourcepub fn is_none(&self, py: Python<'_>) -> bool
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.
Sourcepub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool>
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).
Sourcepub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> Result<D, D::Error>where
D: FromPyObject<'a, 'py>,
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().
Sourcepub fn getattr<'py, N>(
&self,
py: Python<'py>,
attr_name: N,
) -> PyResult<Py<PyAny>>where
N: IntoPyObject<'py, Target = PyString>,
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"))
}Sourcepub fn setattr<'py, N, V>(
&self,
py: Python<'py>,
attr_name: N,
value: V,
) -> PyResult<()>
pub fn setattr<'py, N, V>( &self, py: Python<'py>, attr_name: N, value: V, ) -> PyResult<()>
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)
}Sourcepub fn call<'py, A>(
&self,
py: Python<'py>,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<Py<PyAny>>where
A: PyCallArgs<'py>,
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).
Sourcepub fn call1<'py, A>(&self, py: Python<'py>, args: A) -> PyResult<Py<PyAny>>where
A: PyCallArgs<'py>,
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).
Sourcepub fn call0(&self, py: Python<'_>) -> PyResult<Py<PyAny>>
pub fn call0(&self, py: Python<'_>) -> PyResult<Py<PyAny>>
Calls the object without arguments.
This is equivalent to the Python expression self().
Sourcepub fn call_method<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<Py<PyAny>>
pub fn call_method<'py, N, A>( &self, py: Python<'py>, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Py<PyAny>>
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.
Sourcepub fn call_method1<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
) -> PyResult<Py<PyAny>>
pub fn call_method1<'py, N, A>( &self, py: Python<'py>, name: N, args: A, ) -> PyResult<Py<PyAny>>
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.
Sourcepub fn call_method0<'py, N>(
&self,
py: Python<'py>,
name: N,
) -> PyResult<Py<PyAny>>where
N: IntoPyObject<'py, Target = PyString>,
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.
Sourcepub fn cast_bound<'py, U>(
&self,
py: Python<'py>,
) -> Result<&Bound<'py, U>, CastError<'_, 'py>>where
U: PyTypeCheck,
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(())
})Sourcepub unsafe fn cast_bound_unchecked<'py, U>(
&self,
py: Python<'py>,
) -> &Bound<'py, U>
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>
impl<'a, T> Clone for PyBorrowedUnbound<'a, T>
impl<'a, T> Copy for PyBorrowedUnbound<'a, T>
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>
impl<'a, T> RefUnwindSafe for PyBorrowedUnbound<'a, T>
impl<'a, T> Unpin for PyBorrowedUnbound<'a, T>
impl<'a, T> UnsafeUnpin for PyBorrowedUnbound<'a, T>
impl<'a, T> UnwindSafe for PyBorrowedUnbound<'a, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> SizeHint for Twhere
T: ?Sized,
impl<T> SizeHint for Twhere
T: ?Sized,
Source§default fn lower_bound(&self) -> usize
default fn lower_bound(&self) -> usize
core_io_internals)[u8; 12] could return any value between 0 and
12 inclusively as a correct implementation. Read moreSource§impl<T> SizedTypeProperties for T
impl<T> SizedTypeProperties for T
Source§#[doc(hidden)]const SIZE: usize = _
#[doc(hidden)]const SIZE: usize = _
sized_type_properties)Source§#[doc(hidden)]const ALIGN: usize = _
#[doc(hidden)]const ALIGN: usize = _
sized_type_properties)Source§#[doc(hidden)]const ALIGNMENT: Alignment = _
#[doc(hidden)]const ALIGNMENT: Alignment = _
ptr_alignment_type)Source§#[doc(hidden)]const IS_ZST: bool = _
#[doc(hidden)]const IS_ZST: bool = _
sized_type_properties)Source§#[doc(hidden)]const LAYOUT: Layout = _
#[doc(hidden)]const LAYOUT: Layout = _
sized_type_properties)Source§#[doc(hidden)]const MAX_SLICE_LEN: usize = _
#[doc(hidden)]const MAX_SLICE_LEN: usize = _
sized_type_properties)[Self]. Read more