Struct PyClassGuardMut
pub struct PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,{ /* private fields */ }tls only.Expand description
A wrapper type for a mutably borrowed value from a PyClass
§When not to use PyClassGuardMut
Usually you can use &mut references as method and function receivers and
arguments, and you won’t need to use PyClassGuardMut directly:
use pyo3::prelude::*;
#[pyclass]
struct Number {
inner: u32,
}
#[pymethods]
impl Number {
fn increment(&mut self) {
self.inner += 1;
}
}The #[pymethods] proc macro will generate this wrapper
function (and more), using PyClassGuardMut under the hood:
// The function which is exported to Python looks roughly like the following
unsafe extern "C" fn __pymethod_increment__(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
) -> *mut ::pyo3::ffi::PyObject {
unsafe fn inner<'py>(
py: ::pyo3::Python<'py>,
_slf: *mut ::pyo3::ffi::PyObject,
) -> ::pyo3::PyResult<*mut ::pyo3::ffi::PyObject> {
let function = Number::increment;
let mut holder_0 = ::pyo3::impl_::extract_argument::FunctionArgumentHolder::INIT;
let result = {
let ret = function(::pyo3::impl_::extract_argument::extract_pyclass_ref_mut::<Number>(
unsafe { ::pyo3::impl_::extract_argument::cast_function_argument(py, _slf) },
&mut holder_0,
)?);
{
let result = {
let obj = ret;
::pyo3::impl_::wrap::converter(&obj)
.wrap(obj)
.map_err(::core::convert::Into::<::pyo3::PyErr>::into)
};
::pyo3::impl_::wrap::converter(&result).map_into_ptr(py, result)
}
};
result
}
unsafe {
::pyo3::impl_::trampoline::get_trampoline_function!(noargs, inner)(
_slf,
_args,
)
}
}§When to use PyClassGuardMut
§Using PyClasses from Rust
However, we do need PyClassGuardMut if we want to call its methods
from Rust:
Python::attach(|py| {
let n = Py::new(py, Number { inner: 0 })?;
// We borrow the guard and then dereference
// it to get a mutable reference to Number
let mut guard: PyClassGuardMut<'_, Number> = n.extract(py)?;
let n_mutable: &mut Number = &mut *guard;
n_mutable.increment();
// To avoid panics we must dispose of the
// `PyClassGuardMut` before borrowing again.
drop(guard);
let n_immutable: &Number = &*n.extract::<PyClassGuard<'_, Number>>(py)?;
assert_eq!(n_immutable.inner, 1);
Ok(())
})§Dealing with possibly overlapping mutable references
It is also necessary to use PyClassGuardMut if you can receive mutable
arguments that may overlap. Suppose the following function that swaps the
values of two Numbers:
#[pyfunction]
fn swap_numbers(a: &mut Number, b: &mut Number) {
std::mem::swap(&mut a.inner, &mut b.inner);
}When users pass in the same Number as both arguments, one of the mutable
borrows will fail and raise a RuntimeError:
>>> a = Number()
>>> swap_numbers(a, a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: Already borrowedIt is better to write that function like this:
#[pyfunction]
fn swap_numbers(a: &Bound<'_, Number>, b: &Bound<'_, Number>) -> PyResult<()> {
// Check that the pointers are unequal
if !a.is(b) {
let mut a: PyClassGuardMut<'_, Number> = a.extract()?;
let mut b: PyClassGuardMut<'_, Number> = b.extract()?;
std::mem::swap(&mut a.inner, &mut b.inner);
} else {
// Do nothing - they are the same object, so don't need swapping.
}
Ok(())
}See PyClassGuard and the guide for more information.
Implementations§
§impl<'a, T> PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
impl<'a, T> PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
pub fn map<F, U>(self, f: F) -> PyClassGuardMap<'a, U, true>
pub fn map<F, U>(self, f: F) -> PyClassGuardMap<'a, U, true>
Consumes the PyClassGuardMut and returns a PyClassGuardMap for a component of the
borrowed data
§Examples
#[pyclass]
pub struct MyClass {
data: [i32; 100],
}
let obj = Bound::new(py, MyClass { data: [0; 100] })?;
let mut data = obj.extract::<PyClassGuardMut<'_, MyClass>>()?.map(|c| c.data.as_mut_slice());
data[0] = 42;§impl<'a, T> PyClassGuardMut<'a, T>
impl<'a, T> PyClassGuardMut<'a, T>
pub fn as_super(
&mut self,
) -> &mut PyClassGuardMut<'a, <T as PyClassImpl>::BaseType>
pub fn as_super( &mut self, ) -> &mut PyClassGuardMut<'a, <T as PyClassImpl>::BaseType>
Borrows a mutable reference to PyClassGuardMut<T::BaseType>.
With the help of this method, you can mutate attributes and call
mutating methods on the superclass without consuming the
PyClassGuardMut<T>. This method can also be chained to access the
super-superclass (and so on).
See PyClassGuard::as_super for more.
pub fn into_super(self) -> PyClassGuardMut<'a, <T as PyClassImpl>::BaseType>
pub fn into_super(self) -> PyClassGuardMut<'a, <T as PyClassImpl>::BaseType>
Gets a PyClassGuardMut<T::BaseType>.
See PyClassGuard::into_super for more.
Trait Implementations§
§impl<T> Deref for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
impl<T> Deref for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
§impl<T> DerefMut for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
impl<T> DerefMut for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
§impl<T> Drop for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
impl<T> Drop for PyClassGuardMut<'_, T>where
T: PyClass<Frozen = False>,
§impl<'a, 'py, T> FromPyObject<'a, 'py> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
impl<'a, 'py, T> FromPyObject<'a, 'py> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
§type Error = PyClassGuardMutError<'a, 'py>
type Error = PyClassGuardMutError<'a, 'py>
§fn extract(
obj: Borrowed<'a, 'py, PyAny>,
) -> Result<PyClassGuardMut<'a, T>, <PyClassGuardMut<'a, T> as FromPyObject<'a, 'py>>::Error>
fn extract( obj: Borrowed<'a, 'py, PyAny>, ) -> Result<PyClassGuardMut<'a, T>, <PyClassGuardMut<'a, T> as FromPyObject<'a, 'py>>::Error>
§impl<'a, 'py, T> IntoPyObject<'py> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
impl<'a, 'py, T> IntoPyObject<'py> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
§type Error = Infallible
type Error = Infallible
§fn into_pyobject(
self,
py: Python<'py>,
) -> Result<<PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Output, <PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Error>
fn into_pyobject( self, py: Python<'py>, ) -> Result<<PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Output, <PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Error>
§impl<'a, 'py, T> IntoPyObject<'py> for &PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
impl<'a, 'py, T> IntoPyObject<'py> for &PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
§type Error = Infallible
type Error = Infallible
§fn into_pyobject(
self,
py: Python<'py>,
) -> Result<<&PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Output, <&PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Error>
fn into_pyobject( self, py: Python<'py>, ) -> Result<<&PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Output, <&PyClassGuardMut<'a, T> as IntoPyObject<'py>>::Error>
impl<T> Send for PyClassGuardMut<'_, T>
impl<T> Sync for PyClassGuardMut<'_, T>
§impl<'a, 'py, T> TryFrom<BoundRef<'a, 'py, T>> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
impl<'a, 'py, T> TryFrom<BoundRef<'a, 'py, T>> for PyClassGuardMut<'a, T>where
T: PyClass<Frozen = False>,
§type Error = PyBorrowMutError
type Error = PyBorrowMutError
§fn try_from(
value: BoundRef<'a, 'py, T>,
) -> Result<PyClassGuardMut<'a, T>, <PyClassGuardMut<'a, T> as TryFrom<BoundRef<'a, 'py, T>>>::Error>
fn try_from( value: BoundRef<'a, 'py, T>, ) -> Result<PyClassGuardMut<'a, T>, <PyClassGuardMut<'a, T> as TryFrom<BoundRef<'a, 'py, T>>>::Error>
Auto Trait Implementations§
impl<'a, T> Freeze for PyClassGuardMut<'a, T>
impl<'a, T> RefUnwindSafe for PyClassGuardMut<'a, T>where
T: RefUnwindSafe,
impl<'a, T> Unpin for PyClassGuardMut<'a, T>
impl<'a, T> UnsafeUnpin for PyClassGuardMut<'a, T>
impl<'a, T> UnwindSafe for PyClassGuardMut<'a, T>where
T: RefUnwindSafe,
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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<R> CryptoRng for Rwhere
R: TryCryptoRng<Error = Infallible> + ?Sized,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> 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<T> Pointable for T
impl<T> Pointable for T
§impl<T> PyErrArguments for T
impl<T> PyErrArguments for T
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<R> Rng for Rwhere
R: TryRng<Error = Infallible> + ?Sized,
impl<R> Rng for Rwhere
R: TryRng<Error = Infallible> + ?Sized,
impl<R> RngCore for Rwhere
R: Rng,
§impl<R> RngExt for Rwhere
R: Rng + ?Sized,
impl<R> RngExt for Rwhere
R: Rng + ?Sized,
§fn random<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
fn random<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
StandardUniform distribution. Read more§fn random_iter<T>(self) -> Iter<StandardUniform, Self, T> ⓘwhere
Self: Sized,
StandardUniform: Distribution<T>,
fn random_iter<T>(self) -> Iter<StandardUniform, Self, T> ⓘwhere
Self: Sized,
StandardUniform: Distribution<T>,
§fn random_range<T, R>(&mut self, range: R) -> Twhere
T: SampleUniform,
R: SampleRange<T>,
fn random_range<T, R>(&mut self, range: R) -> Twhere
T: SampleUniform,
R: SampleRange<T>,
§fn random_bool(&mut self, p: f64) -> bool
fn random_bool(&mut self, p: f64) -> bool
p of being true. Read more§fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool
fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool
numerator/denominator of being
true. Read more§fn sample<T, D>(&mut self, distr: D) -> Twhere
D: Distribution<T>,
fn sample<T, D>(&mut self, distr: D) -> Twhere
D: Distribution<T>,
§fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T> ⓘwhere
D: Distribution<T>,
Self: Sized,
fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T> ⓘwhere
D: Distribution<T>,
Self: Sized,
impl<R> TryCryptoRng for R
§impl<R> TryRng for R
impl<R> TryRng for R
§type Error = <<R as Deref>::Target as TryRng>::Error
type Error = <<R as Deref>::Target as TryRng>::Error
§fn try_next_u32(&mut self) -> Result<u32, <R as TryRng>::Error>
fn try_next_u32(&mut self) -> Result<u32, <R as TryRng>::Error>
u32.§fn try_next_u64(&mut self) -> Result<u64, <R as TryRng>::Error>
fn try_next_u64(&mut self) -> Result<u64, <R as TryRng>::Error>
u64.§fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), <R as TryRng>::Error>
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), <R as TryRng>::Error>
dst entirely with random data.