Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/5944.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add `pyo3-ffi::compat::PyObject_HasAttrWithError` & `pyo3-ffi::compat::PyObject_GetOptionalAttr`
1 change: 1 addition & 0 deletions newsfragments/5944.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use `PyObject_HasAttrWithError` in `PyAnyMethods::hasattr`
31 changes: 31 additions & 0 deletions pyo3-ffi/src/compat/py_3_13.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,34 @@ compat_function!(
crate::_PyThreadState_UncheckedGet()
}
);

compat_function!(
originally_defined_for(Py_3_13);

#[inline]
pub unsafe fn PyObject_HasAttrWithError(obj: *mut crate::PyObject, attr_name: *mut crate::PyObject) -> std::ffi::c_int {
let mut res: *mut crate::PyObject = std::ptr::null_mut();
let rc = crate::compat::PyObject_GetOptionalAttr(obj, attr_name, &mut res);
crate::Py_XDECREF(res);
rc
}
);

compat_function!(
originally_defined_for(Py_3_13);

#[inline]
pub unsafe fn PyObject_GetOptionalAttr(obj: *mut crate::PyObject, attr_name: *mut crate::PyObject, result: *mut *mut crate::PyObject,) -> std::ffi::c_int {
*result = crate::PyObject_GetAttr(obj, attr_name);
if !(*result).is_null() {
1
} else if crate::PyErr_Occurred().is_null() {
0
} else if crate::PyErr_ExceptionMatches(crate::PyExc_AttributeError) > 0 {
crate::PyErr_Clear();
0
} else {
-1
}
}
);
82 changes: 29 additions & 53 deletions src/types/any.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::call::PyCallArgs;
use crate::class::basic::CompareOp;
use crate::conversion::{FromPyObject, IntoPyObject};
use crate::err::{PyErr, PyResult};
use crate::exceptions::{PyAttributeError, PyTypeError};
use crate::err::{error_on_minusone, PyErr, PyResult};
use crate::exceptions::PyTypeError;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::impl_::pycell::PyStaticClassObject;
use crate::instance::Bound;
Expand All @@ -11,7 +11,7 @@ use crate::py_result_ext::PyResultExt;
use crate::type_object::{PyTypeCheck, PyTypeInfo};
use crate::types::PySuper;
use crate::types::{PyDict, PyIterator, PyList, PyString, PyType};
use crate::{err, ffi, Borrowed, BoundObject, IntoPyObjectExt, Py, Python};
use crate::{err, ffi, Borrowed, BoundObject, IntoPyObjectExt, Py};
#[allow(deprecated)]
use crate::{DowncastError, DowncastIntoError};
use std::cell::UnsafeCell;
Expand Down Expand Up @@ -980,17 +980,15 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
where
N: IntoPyObject<'py, Target = PyString>,
{
// PyObject_HasAttr suppresses all exceptions, which was the behaviour of `hasattr` in Python 2.
// Use an implementation which suppresses only AttributeError, which is consistent with `hasattr` in Python 3.
fn inner(py: Python<'_>, getattr_result: PyResult<Bound<'_, PyAny>>) -> PyResult<bool> {
match getattr_result {
Ok(_) => Ok(true),
Err(err) if err.is_instance_of::<PyAttributeError>(py) => Ok(false),
Err(e) => Err(e),
}
}

inner(self.py(), self.getattr(attr_name))
let py = self.py();
let result = unsafe {
ffi::compat::PyObject_HasAttrWithError(
self.as_ptr(),
attr_name.into_pyobject(py).map_err(Into::into)?.as_ptr(),
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have generally tried to avoid the .as_ptr() on temporaries like this because the innocent-looking refactoring out to a variable creates a dangling ptr.

I think also it's worth having the fn inner pattern, see e.g. getattr, can pass any: &Bound<'py, PyAny>, attr_name: Borrowed<'_, '_, PyString>,, which can slightly reduce generic code bloat by having the error handling portion only compiled once.

)
};
error_on_minusone(py, result)?;
Ok(result > 0)
}

fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
Expand Down Expand Up @@ -1020,48 +1018,26 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
where
N: IntoPyObject<'py, Target = PyString>,
{
fn inner<'py>(
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be desirable to restore the fn inner pattern here too?

any: &Bound<'py, PyAny>,
attr_name: Borrowed<'_, 'py, PyString>,
) -> PyResult<Option<Bound<'py, PyAny>>> {
#[cfg(Py_3_13)]
{
let mut resp_ptr: *mut ffi::PyObject = std::ptr::null_mut();
match unsafe {
ffi::PyObject_GetOptionalAttr(any.as_ptr(), attr_name.as_ptr(), &mut resp_ptr)
} {
// Attribute found, result is a new strong reference
1 => {
let bound = unsafe { Bound::from_owned_ptr(any.py(), resp_ptr) };
Ok(Some(bound))
}
// Attribute not found, result is NULL
0 => Ok(None),

// An error occurred (other than AttributeError)
_ => Err(PyErr::fetch(any.py())),
}
let py = self.py();
let mut resp_ptr: *mut ffi::PyObject = std::ptr::null_mut();
match unsafe {
ffi::compat::PyObject_GetOptionalAttr(
self.as_ptr(),
attr_name.into_pyobject(py).map_err(Into::into)?.as_ptr(),
&mut resp_ptr,
)
} {
// Attribute found, result is a new strong reference
1 => {
let bound = unsafe { Bound::from_owned_ptr(py, resp_ptr) };
Ok(Some(bound))
Comment on lines +1032 to +1033
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let bound = unsafe { Bound::from_owned_ptr(py, resp_ptr) };
Ok(Some(bound))
Ok(Some(unsafe { resp_ptr.assume_owned_unchecked(py) }))

}
// Attribute not found, result is NULL
0 => Ok(None),

#[cfg(not(Py_3_13))]
{
match any.getattr(attr_name) {
Ok(bound) => Ok(Some(bound)),
Err(err) => {
let err_type = err
.get_type(any.py())
.is(PyType::new::<PyAttributeError>(any.py()));
match err_type {
true => Ok(None),
false => Err(err),
}
}
}
}
// An error occurred (other than AttributeError)
_ => Err(PyErr::fetch(py)),
}

let py = self.py();
inner(self, attr_name.into_pyobject_or_pyerr(py)?.as_borrowed())
}

fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
Expand Down
Loading