Skip to content

Commit

Permalink
adjust FromPyObject implementations to always use 'py lifetime
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Feb 4, 2024
1 parent d772303 commit a0d8dd8
Show file tree
Hide file tree
Showing 21 changed files with 86 additions and 86 deletions.
4 changes: 2 additions & 2 deletions pyo3-macros-backend/src/frompyobject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,8 @@ pub fn build_derive_from_pyobject(tokens: &DeriveInput) -> Result<TokenStream> {
let lt_param = if let Some(lt) = verify_and_get_lifetime(generics)? {
lt.clone()
} else {
trait_generics.params.push(parse_quote!('source));
parse_quote!('source)
trait_generics.params.push(parse_quote!('py));
parse_quote!('py)
};
let mut where_clause: syn::WhereClause = parse_quote!(where);
for param in generics.type_params() {
Expand Down
2 changes: 1 addition & 1 deletion src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ pub unsafe trait Element: Copy {
fn is_compatible_format(format: &CStr) -> bool;
}

impl<'source, T: Element> FromPyObject<'source> for PyBuffer<T> {
impl<'py, T: Element> FromPyObject<'py> for PyBuffer<T> {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<PyBuffer<T>> {
Self::get(obj.as_gil_ref())
}
Expand Down
34 changes: 17 additions & 17 deletions src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ pub trait IntoPy<T>: Sized {
/// depend on the lifetime of the `obj` or the `prepared` variable.
///
/// For example, when extracting `&str` from a Python byte string, the resulting string slice will
/// point to the existing string data (lifetime: `'source`).
/// point to the existing string data (lifetime: `'py`).
/// On the other hand, when extracting `&str` from a Python Unicode string, the preparation step
/// will convert the string to UTF-8, and the resulting string slice will have lifetime `'prepared`.
/// Since which case applies depends on the runtime type of the Python object,
Expand All @@ -219,20 +219,20 @@ pub trait IntoPy<T>: Sized {
/// has two methods `extract` and `extract_bound` which are defaulted to call each other. To avoid
/// infinite recursion, implementors must implement at least one of these methods. The recommendation
/// is to implement `extract_bound` and leave `extract` as the default implementation.
pub trait FromPyObject<'source>: Sized {
pub trait FromPyObject<'py>: Sized {
/// Extracts `Self` from the source GIL Ref `obj`.
///
/// Implementors are encouraged to implement `extract_bound` and leave this method as the
/// default implementation, which will forward calls to `extract_bound`.
fn extract(ob: &'source PyAny) -> PyResult<Self> {
fn extract(ob: &'py PyAny) -> PyResult<Self> {
Self::extract_bound(&ob.as_borrowed())
}

/// Extracts `Self` from the bound smart pointer `obj`.
///
/// Implementors are encouraged to implement this method and leave `extract` defaulted, as
/// this will be most compatible with PyO3's future API.
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
Self::extract(ob.clone().into_gil_ref())
}

Expand Down Expand Up @@ -308,56 +308,56 @@ impl<T: Copy + IntoPy<PyObject>> IntoPy<PyObject> for Cell<T> {
}
}

impl<'a, T: FromPyObject<'a>> FromPyObject<'a> for Cell<T> {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
impl<'py, T: FromPyObject<'py>> FromPyObject<'py> for Cell<T> {
fn extract(ob: &'py PyAny) -> PyResult<Self> {
T::extract(ob).map(Cell::new)
}
}

impl<'a, T> FromPyObject<'a> for &'a PyCell<T>
impl<'py, T> FromPyObject<'py> for &'py PyCell<T>
where
T: PyClass,
{
fn extract(obj: &'a PyAny) -> PyResult<Self> {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
obj.downcast().map_err(Into::into)
}
}

impl<'a, T> FromPyObject<'a> for T
impl<T> FromPyObject<'_> for T
where
T: PyClass + Clone,
{
fn extract(obj: &'a PyAny) -> PyResult<Self> {
fn extract(obj: &PyAny) -> PyResult<Self> {
let cell: &PyCell<Self> = obj.downcast()?;
Ok(unsafe { cell.try_borrow_unguarded()?.clone() })
}
}

impl<'a, T> FromPyObject<'a> for PyRef<'a, T>
impl<'py, T> FromPyObject<'py> for PyRef<'py, T>
where
T: PyClass,
{
fn extract(obj: &'a PyAny) -> PyResult<Self> {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
let cell: &PyCell<T> = obj.downcast()?;
cell.try_borrow().map_err(Into::into)
}
}

impl<'a, T> FromPyObject<'a> for PyRefMut<'a, T>
impl<'py, T> FromPyObject<'py> for PyRefMut<'py, T>
where
T: PyClass<Frozen = False>,
{
fn extract(obj: &'a PyAny) -> PyResult<Self> {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
let cell: &PyCell<T> = obj.downcast()?;
cell.try_borrow_mut().map_err(Into::into)
}
}

impl<'a, T> FromPyObject<'a> for Option<T>
impl<'py, T> FromPyObject<'py> for Option<T>
where
T: FromPyObject<'a>,
T: FromPyObject<'py>,
{
fn extract(obj: &'a PyAny) -> PyResult<Self> {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
if obj.as_ptr() == unsafe { ffi::Py_None() } {
Ok(None)
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/conversions/chrono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ impl<Tz: TimeZone> IntoPy<PyObject> for DateTime<Tz> {
}
}

impl<Tz: TimeZone + for<'a> FromPyObject<'a>> FromPyObject<'_> for DateTime<Tz> {
impl<Tz: TimeZone + for<'py> FromPyObject<'py>> FromPyObject<'_> for DateTime<Tz> {
fn extract_bound(dt: &Bound<'_, PyAny>) -> PyResult<DateTime<Tz>> {
#[cfg(not(Py_LIMITED_API))]
let dt = dt.downcast::<PyDateTime>()?;
Expand Down
8 changes: 4 additions & 4 deletions src/conversions/either.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ where
}

#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
impl<'source, L, R> FromPyObject<'source> for Either<L, R>
impl<'py, L, R> FromPyObject<'py> for Either<L, R>
where
L: FromPyObject<'source>,
R: FromPyObject<'source>,
L: FromPyObject<'py>,
R: FromPyObject<'py>,
{
#[inline]
fn extract_bound(obj: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
if let Ok(l) = obj.extract::<L>() {
Ok(Either::Left(l))
} else if let Ok(r) = obj.extract::<R>() {
Expand Down
14 changes: 7 additions & 7 deletions src/conversions/hashbrown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ where
}
}

impl<'source, K, V, S> FromPyObject<'source> for hashbrown::HashMap<K, V, S>
impl<'py, K, V, S> FromPyObject<'py> for hashbrown::HashMap<K, V, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
V: FromPyObject<'source>,
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> Result<Self, PyErr> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = hashbrown::HashMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict.iter() {
Expand Down Expand Up @@ -90,12 +90,12 @@ where
}
}

impl<'source, K, S> FromPyObject<'source> for hashbrown::HashSet<K, S>
impl<'py, K, S> FromPyObject<'py> for hashbrown::HashSet<K, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
Expand Down
8 changes: 4 additions & 4 deletions src/conversions/indexmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,13 @@ where
}
}

impl<'source, K, V, S> FromPyObject<'source> for indexmap::IndexMap<K, V, S>
impl<'py, K, V, S> FromPyObject<'py> for indexmap::IndexMap<K, V, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
V: FromPyObject<'source>,
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> Result<Self, PyErr> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = indexmap::IndexMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict.iter() {
Expand Down
8 changes: 4 additions & 4 deletions src/conversions/num_bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ bigint_conversion!(BigUint, 0, BigUint::to_bytes_le);
bigint_conversion!(BigInt, 1, BigInt::to_signed_bytes_le);

#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'source> FromPyObject<'source> for BigInt {
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<BigInt> {
impl<'py> FromPyObject<'py> for BigInt {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<BigInt> {
let py = ob.py();
// fast path - checking for subclass of `int` just checks a bit in the type object
let num_owned: Py<PyLong>;
Expand Down Expand Up @@ -159,8 +159,8 @@ impl<'source> FromPyObject<'source> for BigInt {
}

#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'source> FromPyObject<'source> for BigUint {
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<BigUint> {
impl<'py> FromPyObject<'py> for BigUint {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<BigUint> {
let py = ob.py();
// fast path - checking for subclass of `int` just checks a bit in the type object
let num_owned: Py<PyLong>;
Expand Down
10 changes: 5 additions & 5 deletions src/conversions/smallvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ where
}
}

impl<'a, A> FromPyObject<'a> for SmallVec<A>
impl<'py, A> FromPyObject<'py> for SmallVec<A>
where
A: Array,
A::Item: FromPyObject<'a>,
A::Item: FromPyObject<'py>,
{
fn extract_bound(obj: &Bound<'a, PyAny>) -> PyResult<Self> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
if obj.is_instance_of::<PyString>() {
return Err(PyTypeError::new_err("Can't extract `str` to `SmallVec`"));
}
Expand All @@ -72,10 +72,10 @@ where
}
}

fn extract_sequence<'s, A>(obj: &Bound<'s, PyAny>) -> PyResult<SmallVec<A>>
fn extract_sequence<'py, A>(obj: &Bound<'py, PyAny>) -> PyResult<SmallVec<A>>
where
A: Array,
A::Item: FromPyObject<'s>,
A::Item: FromPyObject<'py>,
{
// Types that pass `PySequence_Check` usually implement enough of the sequence protocol
// to support this function and if not, we will only fail extraction safely.
Expand Down
10 changes: 5 additions & 5 deletions src/conversions/std/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@ where
}
}

impl<'a, T, const N: usize> FromPyObject<'a> for [T; N]
impl<'py, T, const N: usize> FromPyObject<'py> for [T; N]
where
T: FromPyObject<'a>,
T: FromPyObject<'py>,
{
fn extract_bound(obj: &Bound<'a, PyAny>) -> PyResult<Self> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
create_array_from_obj(obj)
}
}

fn create_array_from_obj<'s, T, const N: usize>(obj: &Bound<'s, PyAny>) -> PyResult<[T; N]>
fn create_array_from_obj<'py, T, const N: usize>(obj: &Bound<'py, PyAny>) -> PyResult<[T; N]>
where
T: FromPyObject<'s>,
T: FromPyObject<'py>,
{
// Types that pass `PySequence_Check` usually implement enough of the sequence protocol
// to support this function and if not, we will only fail extraction safely.
Expand Down
16 changes: 8 additions & 8 deletions src/conversions/std/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@ where
}
}

impl<'source, K, V, S> FromPyObject<'source> for collections::HashMap<K, V, S>
impl<'py, K, V, S> FromPyObject<'py> for collections::HashMap<K, V, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
V: FromPyObject<'source>,
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> Result<Self, PyErr> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = collections::HashMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict.iter() {
Expand All @@ -88,12 +88,12 @@ where
}
}

impl<'source, K, V> FromPyObject<'source> for collections::BTreeMap<K, V>
impl<'py, K, V> FromPyObject<'py> for collections::BTreeMap<K, V>
where
K: FromPyObject<'source> + cmp::Ord,
V: FromPyObject<'source>,
K: FromPyObject<'py> + cmp::Ord,
V: FromPyObject<'py>,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> Result<Self, PyErr> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = collections::BTreeMap::new();
for (k, v) in dict.iter() {
Expand Down
2 changes: 1 addition & 1 deletion src/conversions/std/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ macro_rules! int_fits_c_long {
}
}

impl<'source> FromPyObject<'source> for $rust_type {
impl<'py> FromPyObject<'py> for $rust_type {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let val: c_long = extract_int!(obj, -1, ffi::PyLong_AsLong)?;
<$rust_type>::try_from(val)
Expand Down
12 changes: 6 additions & 6 deletions src/conversions/std/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ where
}
}

impl<'source, K, S> FromPyObject<'source> for collections::HashSet<K, S>
impl<'py, K, S> FromPyObject<'py> for collections::HashSet<K, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
Expand Down Expand Up @@ -91,11 +91,11 @@ where
}
}

impl<'source, K> FromPyObject<'source> for collections::BTreeSet<K>
impl<'py, K> FromPyObject<'py> for collections::BTreeSet<K>
where
K: FromPyObject<'source> + cmp::Ord,
K: FromPyObject<'py> + cmp::Ord,
{
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
Expand Down
4 changes: 2 additions & 2 deletions src/conversions/std/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ impl<'a> IntoPy<PyObject> for &'a [u8] {
}
}

impl<'a> FromPyObject<'a> for &'a [u8] {
fn extract(obj: &'a PyAny) -> PyResult<Self> {
impl<'py> FromPyObject<'py> for &'py [u8] {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
Ok(obj.downcast::<PyBytes>()?.as_bytes())
}

Expand Down
4 changes: 2 additions & 2 deletions src/conversions/std/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ impl<'a> IntoPy<PyObject> for &'a String {

/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.
impl<'source> FromPyObject<'source> for &'source str {
fn extract(ob: &'source PyAny) -> PyResult<Self> {
impl<'py> FromPyObject<'py> for &'py str {
fn extract(ob: &'py PyAny) -> PyResult<Self> {
ob.downcast::<PyString>()?.to_str()
}

Expand Down
4 changes: 2 additions & 2 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -988,9 +988,9 @@ impl<T> Py<T> {
/// Extracts some type from the Python object.
///
/// This is a wrapper function around `FromPyObject::extract()`.
pub fn extract<'p, D>(&'p self, py: Python<'p>) -> PyResult<D>
pub fn extract<'py, D>(&'py self, py: Python<'py>) -> PyResult<D>
where
D: FromPyObject<'p>,
D: FromPyObject<'py>,
{
FromPyObject::extract(unsafe { py.from_borrowed_ptr(self.as_ptr()) })
}
Expand Down
4 changes: 2 additions & 2 deletions src/types/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -801,9 +801,9 @@ impl PyAny {
///
/// This is a wrapper function around [`FromPyObject::extract()`].
#[inline]
pub fn extract<'a, D>(&'a self) -> PyResult<D>
pub fn extract<'py, D>(&'py self) -> PyResult<D>
where
D: FromPyObject<'a>,
D: FromPyObject<'py>,
{
FromPyObject::extract(self)
}
Expand Down
Loading

0 comments on commit a0d8dd8

Please sign in to comment.