adjust FromPyObject implementations to always use 'py lifetime

This commit is contained in:
David Hewitt 2024-02-04 14:12:35 +00:00
parent 2a741a21e6
commit 0d4df9c19d
21 changed files with 86 additions and 86 deletions

View file

@ -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() {

View file

@ -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())
}

View file

@ -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,
@ -219,12 +219,12 @@ 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())
}
@ -232,7 +232,7 @@ pub trait FromPyObject<'source>: Sized {
///
/// 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())
}
@ -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 {

View file

@ -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>()?;

View file

@ -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>() {

View file

@ -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() {
@ -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) => {

View file

@ -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() {

View file

@ -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>;
@ -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>;

View file

@ -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`"));
}
@ -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.

View file

@ -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.

View file

@ -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() {
@ -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() {

View file

@ -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)

View file

@ -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) => {
@ -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) => {

View file

@ -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())
}

View file

@ -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()
}

View file

@ -996,9 +996,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()) })
}

View file

@ -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)
}

View file

@ -203,8 +203,8 @@ impl<I: SliceIndex<[u8]>> Index<I> for Bound<'_, PyBytes> {
/// If the source object is a `bytes` object, the `Cow` will be borrowed and
/// pointing into the source object, and no copying or heap allocations will happen.
/// If it is a `bytearray`, its contents will be copied to an owned `Cow`.
impl<'source> FromPyObject<'source> for Cow<'source, [u8]> {
fn extract(ob: &'source PyAny) -> PyResult<Self> {
impl<'py> FromPyObject<'py> for Cow<'py, [u8]> {
fn extract(ob: &'py PyAny) -> PyResult<Self> {
if let Ok(bytes) = ob.downcast::<PyBytes>() {
return Ok(Cow::Borrowed(bytes.as_bytes()));
}

View file

@ -95,10 +95,10 @@ impl IntoPy<PyObject> for f64 {
}
}
impl<'source> FromPyObject<'source> for f64 {
impl<'py> FromPyObject<'py> for f64 {
// PyFloat_AsDouble returns -1.0 upon failure
#![allow(clippy::float_cmp)]
fn extract_bound(obj: &Bound<'source, PyAny>) -> PyResult<Self> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
// On non-limited API, .value() uses PyFloat_AS_DOUBLE which
// allows us to have an optimized fast path for the case when
// we have exactly a `float` object (it's not worth going through
@ -142,8 +142,8 @@ impl IntoPy<PyObject> for f32 {
}
}
impl<'source> FromPyObject<'source> for f32 {
fn extract_bound(obj: &Bound<'source, PyAny>) -> PyResult<Self> {
impl<'py> FromPyObject<'py> for f32 {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
Ok(obj.extract::<f64>()? as f32)
}

View file

@ -479,11 +479,11 @@ fn sequence_slice(seq: &PySequence, start: usize, end: usize) -> &PySequence {
index_impls!(PySequence, "sequence", sequence_len, sequence_slice);
impl<'a, T> FromPyObject<'a> for Vec<T>
impl<'py, T> FromPyObject<'py> for Vec<T>
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> {
if obj.is_instance_of::<PyString>() {
return Err(PyTypeError::new_err("Can't extract `str` to `Vec`"));
}
@ -496,9 +496,9 @@ where
}
}
fn extract_sequence<'s, T>(obj: &Bound<'s, PyAny>) -> PyResult<Vec<T>>
fn extract_sequence<'py, T>(obj: &Bound<'py, PyAny>) -> PyResult<Vec<T>>
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.

View file

@ -666,8 +666,8 @@ fn type_output() -> TypeInfo {
}
}
impl<'s, $($T: FromPyObject<'s>),+> FromPyObject<'s> for ($($T,)+) {
fn extract_bound(obj: &Bound<'s, PyAny>) -> PyResult<Self>
impl<'py, $($T: FromPyObject<'py>),+> FromPyObject<'py> for ($($T,)+) {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self>
{
let t = obj.downcast::<PyTuple>()?;
if t.len() == $length {