Struct Borrowed
pub struct Borrowed<'a, 'py, T>(/* private fields */);
dep_pyo3
and std
only.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
).
Implementations§
§impl<'a, 'py, T> Borrowed<'a, 'py, T>
impl<'a, 'py, T> Borrowed<'a, 'py, T>
pub 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(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(())
})
§impl<'a, 'py> Borrowed<'a, 'py, PyAny>
impl<'a, 'py> Borrowed<'a, 'py, PyAny>
pub unsafe fn from_ptr(
py: Python<'py>,
ptr: *mut PyObject,
) -> Borrowed<'a, 'py, PyAny>
pub unsafe fn from_ptr( py: Python<'py>, ptr: *mut PyObject, ) -> Borrowed<'a, 'py, PyAny>
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
.
pub unsafe fn from_ptr_or_opt(
py: Python<'py>,
ptr: *mut PyObject,
) -> Option<Borrowed<'a, 'py, PyAny>> ⓘ
pub unsafe fn from_ptr_or_opt( py: Python<'py>, ptr: *mut PyObject, ) -> Option<Borrowed<'a, 'py, PyAny>> ⓘ
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
.
pub unsafe fn from_ptr_or_err(
py: Python<'py>,
ptr: *mut PyObject,
) -> Result<Borrowed<'a, 'py, PyAny>, PyErr> ⓘ
pub unsafe fn from_ptr_or_err( py: Python<'py>, ptr: *mut PyObject, ) -> Result<Borrowed<'a, 'py, PyAny>, PyErr> ⓘ
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
.
Methods from Deref<Target = Bound<'py, T>>§
pub 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
.
pub fn borrow_mut(&self) -> PyRefMut<'py, T>where
T: PyClass<Frozen = False>,
pub fn borrow_mut(&self) -> PyRefMut<'py, T>where
T: PyClass<Frozen = False>,
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
.
pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError> ⓘ
pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError> ⓘ
pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError> ⓘwhere
T: PyClass<Frozen = False>,
pub fn try_borrow_mut(&self) -> 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
.
pub 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
][macro@crate::pyclass] 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 fn as_super(&self) -> &Bound<'py, <T as PyClassImpl>::BaseType>
pub fn as_super(&self) -> &Bound<'py, <T as PyClassImpl>::BaseType>
Upcast this Bound<PyClass>
to its base type by reference.
If this type defined an explicit base class in its pyclass
declaration
(e.g. #[pyclass(extends = BaseType)]
), the returned type will be
&Bound<BaseType>
. If an explicit base class was not declared, the
return value will be &Bound<PyAny>
(making this method equivalent
to as_any
).
This method is particularly useful for calling methods defined in an
extension trait that has been implemented for Bound<BaseType>
.
See also the into_super
method to upcast by value, and the
PyRef::as_super
/PyRefMut::as_super
methods for upcasting a pyclass
that has already been borrow
ed.
§Example: Calling a method defined on the Bound
base type
use pyo3::prelude::*;
#[pyclass(subclass)]
struct BaseClass;
trait MyClassMethods<'py> {
fn pyrepr(&self) -> PyResult<String>;
}
impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> {
fn pyrepr(&self) -> PyResult<String> {
self.call_method0("__repr__")?.extract()
}
}
#[pyclass(extends = BaseClass)]
struct SubClass;
Python::with_gil(|py| {
let obj = Bound::new(py, (SubClass, BaseClass)).unwrap();
assert!(obj.as_super().pyrepr().is_ok());
})
pub 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 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.
pub 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.
Trait Implementations§
§impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T>
impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T>
§fn as_borrowed(&self) -> Borrowed<'a, 'py, T>
fn as_borrowed(&self) -> Borrowed<'a, 'py, T>
§fn into_bound(self) -> Bound<'py, T>
fn into_bound(self) -> Bound<'py, T>
Bound<'py, T>
]§fn into_any(self) -> <Borrowed<'a, 'py, T> as BoundObject<'py, T>>::Any
fn into_any(self) -> <Borrowed<'a, 'py, T> as BoundObject<'py, T>>::Any
§impl<'a, 'py, T> IntoPyObject<'py> for &Borrowed<'a, 'py, T>
impl<'a, 'py, T> IntoPyObject<'py> for &Borrowed<'a, 'py, T>
§type Output = Borrowed<'a, 'py, <&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Target>
type Output = Borrowed<'a, 'py, <&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Target>
§type Error = Infallible
type Error = Infallible
§fn into_pyobject(
self,
_py: Python<'py>,
) -> Result<<&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Output, <&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Error> ⓘ
fn into_pyobject( self, _py: Python<'py>, ) -> Result<<&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Output, <&Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Error> ⓘ
§impl<'a, 'py, T> IntoPyObject<'py> for Borrowed<'a, 'py, T>
impl<'a, 'py, T> IntoPyObject<'py> for Borrowed<'a, 'py, T>
§type Output = Borrowed<'a, 'py, <Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Target>
type Output = Borrowed<'a, 'py, <Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Target>
§type Error = Infallible
type Error = Infallible
§fn into_pyobject(
self,
_py: Python<'py>,
) -> Result<<Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Output, <Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Error> ⓘ
fn into_pyobject( self, _py: Python<'py>, ) -> Result<<Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Output, <Borrowed<'a, 'py, T> as IntoPyObject<'py>>::Error> ⓘ
§impl PartialEq<&[u8]> for Borrowed<'_, '_, PyBytes>
Compares whether the Python bytes object is equal to the u8.
impl PartialEq<&[u8]> for Borrowed<'_, '_, PyBytes>
Compares whether the Python bytes object is equal to the u8.
In some cases Python equality might be more appropriate; see the note on PyBytes
.
§impl PartialEq<&str> for Borrowed<'_, '_, PyString>
Compares whether the data in the Python string is equal to the given UTF8.
impl PartialEq<&str> for Borrowed<'_, '_, PyString>
Compares whether the data in the Python string is equal to the given UTF8.
In some cases Python equality might be more appropriate; see the note on PyString
.
§impl PartialEq<[u8]> for Borrowed<'_, '_, PyBytes>
Compares whether the Python bytes object is equal to the u8.
impl PartialEq<[u8]> for Borrowed<'_, '_, PyBytes>
Compares whether the Python bytes object is equal to the u8.
In some cases Python equality might be more appropriate; see the note on PyBytes
.
§impl PartialEq<Borrowed<'_, '_, PyBytes>> for &[u8]
Compares whether the Python bytes object is equal to the u8.
impl PartialEq<Borrowed<'_, '_, PyBytes>> for &[u8]
Compares whether the Python bytes object is equal to the u8.
In some cases Python equality might be more appropriate; see the note on PyBytes
.
§impl PartialEq<Borrowed<'_, '_, PyBytes>> for [u8]
Compares whether the Python bytes object is equal to the u8.
impl PartialEq<Borrowed<'_, '_, PyBytes>> for [u8]
Compares whether the Python bytes object is equal to the u8.
In some cases Python equality might be more appropriate; see the note on PyBytes
.
§impl PartialEq<Borrowed<'_, '_, PyString>> for &str
Compares whether the data in the Python string is equal to the given UTF8.
impl PartialEq<Borrowed<'_, '_, PyString>> for &str
Compares whether the data in the Python string is equal to the given UTF8.
In some cases Python equality might be more appropriate; see the note on PyString
.
§impl PartialEq<Borrowed<'_, '_, PyString>> for str
Compares whether the data in the Python string is equal to the given UTF8.
impl PartialEq<Borrowed<'_, '_, PyString>> for str
Compares whether the data in the Python string is equal to the given UTF8.
In some cases Python equality might be more appropriate; see the note on PyString
.
§impl PartialEq<str> for Borrowed<'_, '_, PyString>
Compares whether the data in the Python string is equal to the given UTF8.
impl PartialEq<str> for Borrowed<'_, '_, PyString>
Compares whether the data in the Python string is equal to the given UTF8.
In some cases Python equality might be more appropriate; see the note on PyString
.
§impl<T> ToPyObject for Borrowed<'_, '_, T>
impl<T> ToPyObject for Borrowed<'_, '_, T>
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§
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
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> ByteSized for T
impl<T> ByteSized for T
Source§const BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Source§fn byte_align(&self) -> usize ⓘ
fn byte_align(&self) -> usize ⓘ
Source§fn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Source§impl<T, R> Chain<R> for Twhere
T: ?Sized,
impl<T, R> Chain<R> for Twhere
T: ?Sized,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> ExtAny for T
impl<T> ExtAny for T
Source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Source§impl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
Source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Source§fn mem_align_of_val(&self) -> usize ⓘ
fn mem_align_of_val(&self) -> usize ⓘ
Source§fn mem_size_of_val(&self) -> usize ⓘ
fn mem_size_of_val(&self) -> usize ⓘ
Source§fn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true
if dropping values of this type matters. Read moreSource§fn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self
without running its destructor. Read moreSource§fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Source§unsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice
only.§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Hook for T
impl<T> Hook for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
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§impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
§fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
self
into an owned Python object, dropping type information.§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out
indicating that a T
is niched.