#[repr(transparent)]pub struct Borrowed<'a, 'py, T>(NonNull<PyObject>, PhantomData<&'a Py<T>>, Python<'py>);
Expand description
A borrowed equivalent to Bound
.
The advantage of this over &Bound
is that it avoids the need to have a pointer-to-pointer, as Bound
is already a pointer to an `ffi::PyObject``.
Similarly, this type is Copy
and Clone
, like a shared reference (&T
).
Tuple Fields§
§0: NonNull<PyObject>
§1: PhantomData<&'a Py<T>>
§2: Python<'py>
Implementations§
source§impl<'py, T> Borrowed<'_, 'py, T>
impl<'py, T> Borrowed<'_, 'py, T>
sourcepub fn to_owned(self) -> Bound<'py, T>
pub fn to_owned(self) -> Bound<'py, T>
Creates a new owned Bound<T>
from this borrowed reference by
increasing the reference count.
§Example
use pyo3::{prelude::*, types::PyTuple};
Python::with_gil(|py| -> PyResult<()> {
let tuple = PyTuple::new_bound(py, [1, 2, 3]);
// borrows from `tuple`, so can only be
// used while `tuple` stays alive
let borrowed = tuple.get_borrowed_item(0)?;
// creates a new owned reference, which
// can be used indendently of `tuple`
let bound = borrowed.to_owned();
drop(tuple);
assert_eq!(bound.extract::<i32>().unwrap(), 1);
Ok(())
})
source§impl<'a, 'py> Borrowed<'a, 'py, PyAny>
impl<'a, 'py> Borrowed<'a, 'py, PyAny>
sourcepub unsafe fn from_ptr(py: Python<'py>, ptr: *mut PyObject) -> Self
pub unsafe fn from_ptr(py: Python<'py>, ptr: *mut PyObject) -> Self
Constructs a new Borrowed<'a, 'py, PyAny>
from a pointer. Panics if ptr
is null.
Prefer to use Bound::from_borrowed_ptr
, as that avoids the major safety risk
of needing to precisely define the lifetime 'a
for which the borrow is valid.
§Safety
ptr
must be a valid pointer to a Python object- similar to
std::slice::from_raw_parts
, the lifetime'a
is completely defined by the caller and it is the caller’s responsibility to ensure that the reference this is derived from is valid for the lifetime'a
.
sourcepub unsafe fn from_ptr_or_opt(
py: Python<'py>,
ptr: *mut PyObject
) -> Option<Self>
pub unsafe fn from_ptr_or_opt( py: Python<'py>, ptr: *mut PyObject ) -> Option<Self>
Constructs a new Borrowed<'a, 'py, PyAny>
from a pointer. Returns None
if ptr
is null.
Prefer to use Bound::from_borrowed_ptr_or_opt
, as that avoids the major safety risk
of needing to precisely define the lifetime 'a
for which the borrow is valid.
§Safety
ptr
must be a valid pointer to a Python object, or null- similar to
std::slice::from_raw_parts
, the lifetime'a
is completely defined by the caller and it is the caller’s responsibility to ensure that the reference this is derived from is valid for the lifetime'a
.
sourcepub unsafe fn from_ptr_or_err(
py: Python<'py>,
ptr: *mut PyObject
) -> PyResult<Self>
pub unsafe fn from_ptr_or_err( py: Python<'py>, ptr: *mut PyObject ) -> PyResult<Self>
Constructs a new Borrowed<'a, 'py, PyAny>
from a pointer. Returns an Err
by calling PyErr::fetch
if ptr
is null.
Prefer to use Bound::from_borrowed_ptr_or_err
, as that avoids the major safety risk
of needing to precisely define the lifetime 'a
for which the borrow is valid.
§Safety
ptr
must be a valid pointer to a Python object, or null- similar to
std::slice::from_raw_parts
, the lifetime'a
is completely defined by the caller and it is the caller’s responsibility to ensure that the reference this is derived from is valid for the lifetime'a
.
sourcepub(crate) unsafe fn from_ptr_unchecked(
py: Python<'py>,
ptr: *mut PyObject
) -> Self
pub(crate) unsafe fn from_ptr_unchecked( py: Python<'py>, ptr: *mut PyObject ) -> Self
§Safety
This is similar to std::slice::from_raw_parts
, the lifetime 'a
is completely defined by
the caller and it’s the caller’s responsibility to ensure that the reference this is
derived from is valid for the lifetime 'a
.
pub(crate) fn downcast<T>(
self
) -> Result<Borrowed<'a, 'py, T>, DowncastError<'a, 'py>>where
T: PyTypeCheck,
gil-refs
only.sourcepub(crate) unsafe fn downcast_unchecked<T>(self) -> Borrowed<'a, 'py, T>
pub(crate) unsafe fn downcast_unchecked<T>(self) -> Borrowed<'a, 'py, T>
Converts this PyAny
to a concrete Python type without checking validity.
§Safety
Callers must ensure that the type is valid or risk type confusion.
source§impl<'py, T> Borrowed<'py, 'py, T>where
T: HasPyGilRef,
impl<'py, T> Borrowed<'py, 'py, T>where
T: HasPyGilRef,
pub(crate) fn into_gil_ref(self) -> &'py T::AsRefTarget
source§impl<'a> Borrowed<'a, '_, PyByteArray>
impl<'a> Borrowed<'a, '_, PyByteArray>
source§impl<'a, 'py> Borrowed<'a, 'py, PyDict>
impl<'a, 'py> Borrowed<'a, 'py, PyDict>
sourcepub(crate) unsafe fn iter_borrowed(self) -> BorrowedDictIter<'a, 'py> ⓘ
pub(crate) unsafe fn iter_borrowed(self) -> BorrowedDictIter<'a, 'py> ⓘ
Iterates over the contents of this dictionary without incrementing reference counts.
§Safety
It must be known that this dictionary will not be modified during iteration.
source§impl<'py> Borrowed<'_, 'py, PyIterator>
impl<'py> Borrowed<'_, 'py, PyIterator>
source§impl<'a> Borrowed<'a, '_, PyString>
impl<'a> Borrowed<'a, '_, PyString>
pub(crate) fn to_str(self) -> PyResult<&'a str>
Py_3_10
or non-Py_LIMITED_API
only.pub(crate) fn to_cow(self) -> PyResult<Cow<'a, str>>
fn to_string_lossy(self) -> Cow<'a, str>
unsafe fn data(self) -> PyResult<PyStringData<'a>>
Py_LIMITED_API
nor GraalPy
nor PyPy
.source§impl<'a, 'py> Borrowed<'a, 'py, PyTuple>
impl<'a, 'py> Borrowed<'a, 'py, PyTuple>
fn get_borrowed_item(self, index: usize) -> PyResult<Borrowed<'a, 'py, PyAny>>
unsafe fn get_borrowed_item_unchecked( self, index: usize ) -> Borrowed<'a, 'py, PyAny>
Py_LIMITED_API
nor PyPy
nor GraalPy
.pub(crate) fn iter_borrowed(self) -> BorrowedTupleIterator<'a, 'py> ⓘ
Methods from Deref<Target = Bound<'py, T>>§
sourcepub fn borrow(&self) -> PyRef<'py, T>
pub fn borrow(&self) -> 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.
§Examples
#[pyclass]
struct Foo {
inner: u8,
}
Python::with_gil(|py| -> PyResult<()> {
let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
let inner: &u8 = &foo.borrow().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(&self) -> PyRefMut<'py, T>
pub fn borrow_mut(&self) -> PyRefMut<'py, T>
Mutably borrows the value T
.
This borrow lasts while the returned PyRefMut
exists.
§Examples
#[pyclass]
struct Foo {
inner: u8,
}
Python::with_gil(|py| -> PyResult<()> {
let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
foo.borrow_mut().inner = 35;
assert_eq!(foo.borrow().inner, 35);
Ok(())
})?;
§Panics
Panics if the value is currently borrowed. For a non-panicking variant, use
try_borrow_mut
.
sourcepub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError>
pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError>
sourcepub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
pub fn try_borrow_mut(&self) -> 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
.
sourcepub fn get(&self) -> &T
pub fn get(&self) -> &T
Provide an immutable borrow of the value T
without acquiring the GIL.
This is available if the class is frozen
and Sync
.
§Examples
use std::sync::atomic::{AtomicUsize, Ordering};
#[pyclass(frozen)]
struct FrozenCounter {
value: AtomicUsize,
}
Python::with_gil(|py| {
let counter = FrozenCounter { value: AtomicUsize::new(0) };
let py_counter = Bound::new(py, counter).unwrap();
py_counter.get().value.fetch_add(1, Ordering::Relaxed);
});
pub(crate) fn get_class_object(&self) -> &PyClassObject<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.
sourcepub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T>
pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T>
Casts this Bound<T>
to a Borrowed<T>
smart pointer.
sourcepub fn as_unbound(&self) -> &Py<T>
pub fn as_unbound(&self) -> &Py<T>
Removes the connection for this Bound<T>
from the GIL, allowing
it to cross thread boundaries, without transferring ownership.
sourcepub fn as_gil_ref(&'py self) -> &'py T::AsRefTargetwhere
T: HasPyGilRef,
pub fn as_gil_ref(&'py self) -> &'py T::AsRefTargetwhere
T: HasPyGilRef,
Casts this Bound<T>
as the corresponding “GIL Ref” type.
This is a helper to be used for migration from the deprecated “GIL Refs” API.
sourcepub(crate) fn lookup_special<N>(
&self,
attr_name: N
) -> PyResult<Option<Bound<'py, PyAny>>>
pub(crate) fn lookup_special<N>( &self, attr_name: N ) -> PyResult<Option<Bound<'py, PyAny>>>
Retrieve an attribute value, skipping the instance dictionary during the lookup but still binding the object to the instance.
This is useful when trying to resolve Python’s “magic” methods like __getitem__
, which
are looked up starting from the type object. This returns an Option
as it is not
typically a direct error for the special lookup to fail, as magic methods are optional in
many situations in which they might be called.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern attr_name
.
Trait Implementations§
source§impl<'py> Add for Borrowed<'_, 'py, PyComplex>
Available on neither Py_LIMITED_API
nor PyPy
nor GraalPy
.
impl<'py> Add for Borrowed<'_, 'py, PyComplex>
Py_LIMITED_API
nor PyPy
nor GraalPy
.source§impl<'py> Div for Borrowed<'_, 'py, PyComplex>
Available on neither Py_LIMITED_API
nor PyPy
nor GraalPy
.
impl<'py> Div for Borrowed<'_, 'py, PyComplex>
Py_LIMITED_API
nor PyPy
nor GraalPy
.source§impl<'py> Mul for Borrowed<'_, 'py, PyComplex>
Available on neither Py_LIMITED_API
nor PyPy
nor GraalPy
.
impl<'py> Mul for Borrowed<'_, 'py, PyComplex>
Py_LIMITED_API
nor PyPy
nor GraalPy
.source§impl<'py> Neg for Borrowed<'_, 'py, PyComplex>
Available on neither Py_LIMITED_API
nor PyPy
nor GraalPy
.
impl<'py> Neg for Borrowed<'_, 'py, PyComplex>
Py_LIMITED_API
nor PyPy
nor GraalPy
.source§impl<'py> Sub for Borrowed<'_, 'py, PyComplex>
Available on neither Py_LIMITED_API
nor PyPy
nor GraalPy
.
impl<'py> Sub for Borrowed<'_, 'py, PyComplex>
Py_LIMITED_API
nor PyPy
nor GraalPy
.source§impl<T> ToPyObject for Borrowed<'_, '_, T>
impl<T> ToPyObject for Borrowed<'_, '_, T>
source§impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &Borrowed<'_, 'py, PyModule>
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &Borrowed<'_, 'py, PyModule>
fn wrap_pyfunction( self, method_def: &PyMethodDef ) -> PyResult<Bound<'py, PyCFunction>>
source§impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Borrowed<'_, 'py, PyModule>
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Borrowed<'_, 'py, PyModule>
fn wrap_pyfunction( self, method_def: &PyMethodDef ) -> PyResult<Bound<'py, PyCFunction>>
impl<T> Copy for Borrowed<'_, '_, T>
Auto Trait Implementations§
impl<'a, 'py, T> Freeze for Borrowed<'a, 'py, T>
impl<'a, 'py, T> RefUnwindSafe for Borrowed<'a, 'py, T>where
T: RefUnwindSafe,
impl<'a, 'py, T> !Send for Borrowed<'a, 'py, T>
impl<'a, 'py, T> !Sync for Borrowed<'a, 'py, T>
impl<'a, 'py, T> Unpin for Borrowed<'a, 'py, T>
impl<'a, 'py, T> UnwindSafe for Borrowed<'a, 'py, T>where
T: RefUnwindSafe,
Blanket Implementations§
source§impl<T> AssertNotZeroSized for T
impl<T> AssertNotZeroSized for T
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> 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 more