Skip to content
Merged
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/5985.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`getattr_opt` now correctly treats `AttributeError` subclasses as missing attributes on Python < 3.13.
25 changes: 25 additions & 0 deletions pyo3-ffi/src/compat/py_3_13.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,28 @@ compat_function!(
0
}
);

compat_function!(
originally_defined_for(Py_3_13);

#[inline]
pub unsafe fn PyObject_GetOptionalAttr(
obj: *mut crate::PyObject,
name: *mut crate::PyObject,
result: *mut *mut crate::PyObject,
) -> std::ffi::c_int {
use crate::{PyErr_Clear, PyErr_ExceptionMatches, PyExc_AttributeError, PyObject_GetAttr};

let attr = PyObject_GetAttr(obj, name);
if !attr.is_null() {
*result = attr;
return 1; // found
}
*result = std::ptr::null_mut();
if PyErr_ExceptionMatches(PyExc_AttributeError) != 0 {
PyErr_Clear();
return 0; // not found
}
-1 // other error
}
);
74 changes: 41 additions & 33 deletions src/types/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1024,39 +1024,20 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
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())),
}
}

#[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),
}
}
}
let mut resp_ptr: *mut ffi::PyObject = std::ptr::null_mut();
match unsafe {
ffi::compat::PyObject_GetOptionalAttr(
any.as_ptr(),
attr_name.as_ptr(),
&mut resp_ptr,
)
} {
// Attribute found, result is a new strong reference
1 => Ok(Some(unsafe { Bound::from_owned_ptr(any.py(), resp_ptr) })),
// Attribute not found
0 => Ok(None),
// An error occurred (other than AttributeError)
_ => Err(PyErr::fetch(any.py())),
}
}

Expand Down Expand Up @@ -1789,6 +1770,33 @@ class Test:
});
}

#[test]
fn test_getattr_opt_attribute_error_subclass() {
Python::attach(|py| {
let module = PyModule::from_code(
py,
cr#"
class CustomAttrError(AttributeError):
pass

class Obj:
@property
def missing(self):
raise CustomAttrError("not here")
"#,
c"test.py",
&generate_unique_module_name("test"),
)
.unwrap();

let obj = module.getattr("Obj").unwrap().call0().unwrap();

// An AttributeError subclass should be treated as "attribute not found"
let result = obj.getattr_opt("missing").unwrap();
assert!(result.is_none());
});
}

#[test]
fn test_call_for_non_existing_method() {
Python::attach(|py| {
Expand Down
Loading