diff --git a/src/derive_utils.rs b/src/derive_utils.rs index 25ea7f89fa7..242cdf68faa 100644 --- a/src/derive_utils.rs +++ b/src/derive_utils.rs @@ -4,7 +4,29 @@ //! Functionality for the code generated by the derive backend -use crate::{types::PyModule, Python}; +use crate::{types::PyModule, PyCell, PyClass, PyErr, Python}; + +/// A trait for types that can be borrowed from a cell. +/// +/// This serves to unify the use of `PyRef` and `PyRefMut` in automatically +/// derived code, since both types can be obtained from a `PyCell`. +#[doc(hidden)] +pub trait TryFromPyCell<'a, T: PyClass>: Sized { + type Error: Into; + fn try_from_pycell(cell: &'a crate::PyCell) -> Result; +} + +impl<'a, T, R> TryFromPyCell<'a, T> for R +where + T: 'a + PyClass, + R: std::convert::TryFrom<&'a PyCell>, + R::Error: Into, +{ + type Error = R::Error; + fn try_from_pycell(cell: &'a crate::PyCell) -> Result { + >>::try_from(cell) + } +} /// Enum to abstract over the arguments of Python function wrappers. pub enum PyFunctionArguments<'a> {