Skip to content

Commit

Permalink
fix deprecated gil refs in function arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Mar 20, 2024
1 parent e5405d1 commit 7a342de
Show file tree
Hide file tree
Showing 31 changed files with 307 additions and 189 deletions.
2 changes: 1 addition & 1 deletion pyo3-macros-backend/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::Result;

pub(crate) struct Holders {
pub struct Holders {
holders: Vec<syn::Ident>,
gil_refs_checkers: Vec<syn::Ident>,
}
Expand Down
3 changes: 2 additions & 1 deletion pyo3-macros-backend/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -736,10 +736,11 @@ fn impl_simple_enum(
fn __pyo3__richcmp__(
&self,
py: #pyo3_path::Python,
other: &#pyo3_path::PyAny,
other: &#pyo3_path::Bound<'_, #pyo3_path::PyAny>,
op: #pyo3_path::basic::CompareOp
) -> #pyo3_path::PyResult<#pyo3_path::PyObject> {
use #pyo3_path::conversion::ToPyObject;
use #pyo3_path::types::PyAnyMethods;
use ::core::result::Result::*;
match op {
#pyo3_path::basic::CompareOp::Eq => {
Expand Down
25 changes: 18 additions & 7 deletions pyo3-macros-backend/src/pymethod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,9 @@ impl Ty {
extract_error_mode,
holders,
&name_str,
quote! { #ident },ctx
quote! { #ident },
arg.ty.span(),
ctx
),
Ty::MaybeNullObject => extract_object(
extract_error_mode,
Expand All @@ -996,32 +998,40 @@ impl Ty {
} else {
#ident
}
},ctx
},
arg.ty.span(),
ctx
),
Ty::NonNullObject => extract_object(
extract_error_mode,
holders,
&name_str,
quote! { #ident.as_ptr() },ctx
quote! { #ident.as_ptr() },
arg.ty.span(),
ctx
),
Ty::IPowModulo => extract_object(
extract_error_mode,
holders,
&name_str,
quote! { #ident.as_ptr() },ctx
quote! { #ident.as_ptr() },
arg.ty.span(),
ctx
),
Ty::CompareOp => extract_error_mode.handle_error(
quote! {
#pyo3_path::class::basic::CompareOp::from_raw(#ident)
.ok_or_else(|| #pyo3_path::exceptions::PyValueError::new_err("invalid comparison operator"))
},ctx
},
ctx
),
Ty::PySsizeT => {
let ty = arg.ty;
extract_error_mode.handle_error(
quote! {
::std::convert::TryInto::<#ty>::try_into(#ident).map_err(|e| #pyo3_path::exceptions::PyValueError::new_err(e.to_string()))
},ctx
},
ctx
)
}
// Just pass other types through unmodified
Expand All @@ -1035,11 +1045,12 @@ fn extract_object(
holders: &mut Holders,
name: &str,
source_ptr: TokenStream,
span: Span,
ctx: &Ctx,
) -> TokenStream {
let Ctx { pyo3_path } = ctx;
let holder = holders.push_holder(Span::call_site());
let gil_refs_checker = holders.push_gil_refs_checker(Span::call_site());
let gil_refs_checker = holders.push_gil_refs_checker(span);
let extracted = extract_error_mode.handle_error(
quote! {
#pyo3_path::impl_::extract_argument::extract_argument(
Expand Down
6 changes: 3 additions & 3 deletions pytests/src/buf_and_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ impl BytesExtractor {
}

#[staticmethod]
pub fn from_bytes(bytes: &PyBytes) -> PyResult<usize> {
pub fn from_bytes(bytes: &Bound<'_, PyBytes>) -> PyResult<usize> {
let byte_vec: Vec<u8> = bytes.extract()?;
Ok(byte_vec.len())
}

#[staticmethod]
pub fn from_str(string: &PyString) -> PyResult<usize> {
pub fn from_str(string: &Bound<'_, PyString>) -> PyResult<usize> {
let rust_string: String = string.extract()?;
Ok(rust_string.len())
}

#[staticmethod]
pub fn from_str_lossy(string: &PyString) -> usize {
pub fn from_str_lossy(string: &Bound<'_, PyString>) -> usize {
let rust_string_lossy: String = string.to_string_lossy().to_string();
rust_string_lossy.len()
}
Expand Down
34 changes: 15 additions & 19 deletions pytests/src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ fn make_date(py: Python<'_>, year: i32, month: u8, day: u8) -> PyResult<Bound<'_
}

#[pyfunction]
fn get_date_tuple<'p>(py: Python<'p>, d: &PyDate) -> Bound<'p, PyTuple> {
PyTuple::new_bound(py, [d.get_year(), d.get_month() as i32, d.get_day() as i32])
fn get_date_tuple<'py>(d: &Bound<'py, PyDate>) -> Bound<'py, PyTuple> {
PyTuple::new_bound(
d.py(),
[d.get_year(), d.get_month() as i32, d.get_day() as i32],
)
}

#[pyfunction]
Expand Down Expand Up @@ -48,9 +51,9 @@ fn time_with_fold<'py>(
}

#[pyfunction]
fn get_time_tuple<'p>(py: Python<'p>, dt: &PyTime) -> Bound<'p, PyTuple> {
fn get_time_tuple<'py>(dt: &Bound<'py, PyTime>) -> Bound<'py, PyTuple> {
PyTuple::new_bound(
py,
dt.py(),
[
dt.get_hour() as u32,
dt.get_minute() as u32,
Expand All @@ -61,9 +64,9 @@ fn get_time_tuple<'p>(py: Python<'p>, dt: &PyTime) -> Bound<'p, PyTuple> {
}

#[pyfunction]
fn get_time_tuple_fold<'p>(py: Python<'p>, dt: &PyTime) -> Bound<'p, PyTuple> {
fn get_time_tuple_fold<'py>(dt: &Bound<'py, PyTime>) -> Bound<'py, PyTuple> {
PyTuple::new_bound(
py,
dt.py(),
[
dt.get_hour() as u32,
dt.get_minute() as u32,
Expand Down Expand Up @@ -123,9 +126,9 @@ fn make_datetime<'py>(
}

#[pyfunction]
fn get_datetime_tuple<'py>(py: Python<'py>, dt: &Bound<'py, PyDateTime>) -> Bound<'py, PyTuple> {
fn get_datetime_tuple<'py>(dt: &Bound<'py, PyDateTime>) -> Bound<'py, PyTuple> {
PyTuple::new_bound(
py,
dt.py(),
[
dt.get_year(),
dt.get_month() as i32,
Expand All @@ -139,12 +142,9 @@ fn get_datetime_tuple<'py>(py: Python<'py>, dt: &Bound<'py, PyDateTime>) -> Boun
}

#[pyfunction]
fn get_datetime_tuple_fold<'py>(
py: Python<'py>,
dt: &Bound<'py, PyDateTime>,
) -> Bound<'py, PyTuple> {
fn get_datetime_tuple_fold<'py>(dt: &Bound<'py, PyDateTime>) -> Bound<'py, PyTuple> {
PyTuple::new_bound(
py,
dt.py(),
[
dt.get_year(),
dt.get_month() as i32,
Expand Down Expand Up @@ -187,12 +187,8 @@ impl TzClass {
TzClass {}
}

fn utcoffset<'py>(
&self,
py: Python<'py>,
_dt: &Bound<'py, PyDateTime>,
) -> PyResult<Bound<'py, PyDelta>> {
PyDelta::new_bound(py, 0, 3600, 0, true)
fn utcoffset<'py>(&self, dt: &Bound<'py, PyDateTime>) -> PyResult<Bound<'py, PyDelta>> {
PyDelta::new_bound(dt.py(), 0, 3600, 0, true)
}

fn tzname(&self, _dt: &Bound<'_, PyDateTime>) -> String {
Expand Down
2 changes: 1 addition & 1 deletion pytests/src/dict_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl DictSize {
DictSize { expected }
}

fn iter_dict(&mut self, _py: Python<'_>, dict: &PyDict) -> PyResult<u32> {
fn iter_dict(&mut self, _py: Python<'_>, dict: &Bound<'_, PyDict>) -> PyResult<u32> {
let mut seen = 0u32;
for (sym, values) in dict {
seen += 1;
Expand Down
4 changes: 2 additions & 2 deletions pytests/src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ fn issue_219() {
}

#[pyfunction]
fn get_type_full_name(obj: &PyAny) -> PyResult<Cow<'_, str>> {
obj.get_type().name()
fn get_type_full_name(obj: &Bound<'_, PyAny>) -> PyResult<String> {
obj.get_type().name().map(Cow::into_owned)
}

#[pyfunction]
Expand Down
2 changes: 1 addition & 1 deletion pytests/src/objstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ impl ObjStore {
ObjStore::default()
}

fn push(&mut self, py: Python<'_>, obj: &PyAny) {
fn push(&mut self, py: Python<'_>, obj: &Bound<'_, PyAny>) {
self.obj.push(obj.to_object(py));
}
}
Expand Down
2 changes: 1 addition & 1 deletion pytests/src/pyclasses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ struct AssertingBaseClassGilRef;
impl AssertingBaseClassGilRef {
#[new]
#[classmethod]
fn new(cls: &PyType, expected_type: &PyType) -> PyResult<Self> {
fn new(cls: &PyType, expected_type: &Bound<'_, PyType>) -> PyResult<Self> {
if !cls.is(expected_type) {
return Err(PyValueError::new_err(format!(
"{:?} != {:?}",
Expand Down
4 changes: 2 additions & 2 deletions src/coroutine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
exceptions::{PyAttributeError, PyRuntimeError, PyStopIteration},
panic::PanicException,
types::{string::PyStringMethods, PyIterator, PyString},
IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python,
Bound, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python,
};

pub(crate) mod cancel;
Expand Down Expand Up @@ -143,7 +143,7 @@ impl Coroutine {
}
}

fn send(&mut self, py: Python<'_>, _value: &PyAny) -> PyResult<PyObject> {
fn send(&mut self, py: Python<'_>, _value: &Bound<'_, PyAny>) -> PyResult<PyObject> {
self.poll(py, None)
}

Expand Down
2 changes: 1 addition & 1 deletion src/coroutine/waker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl LoopAndFuture {
/// Future can be cancelled by the event loop before being waken.
/// See <https://github.com/python/cpython/blob/main/Lib/asyncio/tasks.py#L452C5-L452C5>
#[pyfunction(crate = "crate")]
fn release_waiter(future: &PyAny) -> PyResult<()> {
fn release_waiter(future: &Bound<'_, PyAny>) -> PyResult<()> {
let done = future.call_method0(intern!(future.py(), "done"))?;
if !done.extract::<bool>()? {
future.call_method1(intern!(future.py(), "set_result"), (future.py().None(),))?;
Expand Down
2 changes: 1 addition & 1 deletion src/pycell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,12 @@
//!
//! It is better to write that function like this:
//! ```rust
//! # #![allow(deprecated)]
//! # use pyo3::prelude::*;
//! # #[pyclass]
//! # pub struct Number {
//! # inner: u32,
//! # }
//! # #[allow(deprecated)]
//! #[pyfunction]
//! fn swap_numbers(a: &PyCell<Number>, b: &PyCell<Number>) {
//! // Check that the pointers are unequal
Expand Down
52 changes: 31 additions & 21 deletions src/tests/hygiene/pymethods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Dummy {
}

fn __format__(&self, format_spec: ::std::string::String) -> ::std::string::String {
::std::panic!("unimplemented isn't hygienic before 1.50")
::std::unimplemented!()
}

fn __lt__(&self, other: &Self) -> bool {
Expand Down Expand Up @@ -63,12 +63,12 @@ impl Dummy {
// Customizing attribute access
//////////////////////

fn __getattr__(&self, name: ::std::string::String) -> &crate::PyAny {
::std::panic!("unimplemented isn't hygienic before 1.50")
fn __getattr__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> {
::std::unimplemented!()
}

fn __getattribute__(&self, name: ::std::string::String) -> &crate::PyAny {
::std::panic!("unimplemented isn't hygienic before 1.50")
fn __getattribute__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> {
::std::unimplemented!()
}

fn __setattr__(&mut self, name: ::std::string::String, value: ::std::string::String) {}
Expand All @@ -85,17 +85,27 @@ impl Dummy {

fn __get__(
&self,
instance: &crate::PyAny,
owner: &crate::PyAny,
) -> crate::PyResult<&crate::PyAny> {
::std::panic!("unimplemented isn't hygienic before 1.50")
instance: &crate::Bound<'_, crate::PyAny>,
owner: &crate::Bound<'_, crate::PyAny>,
) -> crate::PyResult<&crate::Bound<'_, crate::PyAny>> {
::std::unimplemented!()
}

fn __set__(&self, instance: &crate::PyAny, owner: &crate::PyAny) {}
fn __set__(
&self,
instance: &crate::Bound<'_, crate::PyAny>,
owner: &crate::Bound<'_, crate::PyAny>,
) {
}

fn __delete__(&self, instance: &crate::PyAny) {}
fn __delete__(&self, instance: &crate::Bound<'_, crate::PyAny>) {}

fn __set_name__(&self, owner: &crate::PyAny, name: &crate::PyAny) {}
fn __set_name__(
&self,
owner: &crate::Bound<'_, crate::PyAny>,
name: &crate::Bound<'_, crate::PyAny>,
) {
}

//////////////////////
// Implementing Descriptors
Expand Down Expand Up @@ -323,9 +333,9 @@ impl Dummy {

fn __exit__(
&mut self,
exc_type: &crate::PyAny,
exc_value: &crate::PyAny,
traceback: &crate::PyAny,
exc_type: &crate::Bound<'_, crate::PyAny>,
exc_value: &crate::Bound<'_, crate::PyAny>,
traceback: &crate::Bound<'_, crate::PyAny>,
) {
}

Expand Down Expand Up @@ -361,9 +371,9 @@ impl Dummy {

fn __aexit__(
&mut self,
exc_type: &crate::PyAny,
exc_value: &crate::PyAny,
traceback: &crate::PyAny,
exc_type: &crate::Bound<'_, crate::PyAny>,
exc_value: &crate::Bound<'_, crate::PyAny>,
traceback: &crate::Bound<'_, crate::PyAny>,
) {
}

Expand All @@ -378,10 +388,10 @@ impl Dummy {
#[pyo3(signature = (*_args, **_kwds))]
fn __call__(
&self,
_args: &crate::types::PyTuple,
_kwds: ::std::option::Option<&crate::types::PyDict>,
_args: &crate::Bound<'_, crate::types::PyTuple>,
_kwds: ::std::option::Option<&crate::Bound<'_, crate::types::PyDict>>,
) -> crate::PyResult<i32> {
::std::panic!("unimplemented isn't hygienic before 1.50")
::std::unimplemented!()
}
#[new]
fn new(a: u8) -> Self {
Expand Down
Loading

0 comments on commit 7a342de

Please sign in to comment.