Skip to content

add PyObject_HasAttrWithError & use it in PyAnyMethods::hasattr#5944

Open
bschoenmaeckers wants to merge 3 commits intoPyO3:mainfrom
bschoenmaeckers:hasattr
Open

add PyObject_HasAttrWithError & use it in PyAnyMethods::hasattr#5944
bschoenmaeckers wants to merge 3 commits intoPyO3:mainfrom
bschoenmaeckers:hasattr

Conversation

@bschoenmaeckers
Copy link
Copy Markdown
Member

closes #5940

@bschoenmaeckers bschoenmaeckers force-pushed the hasattr branch 3 times, most recently from b7788e9 to 03bea8a Compare April 3, 2026 15:04
@bschoenmaeckers bschoenmaeckers force-pushed the hasattr branch 2 times, most recently from 0e7f4b4 to 90c7d67 Compare April 3, 2026 15:32
Copy link
Copy Markdown
Member

@davidhewitt davidhewitt left a comment

Choose a reason for hiding this comment

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

Thanks, a few suggestions to this one.

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.

Comment on lines +1032 to +1033
let bound = unsafe { Bound::from_owned_ptr(py, resp_ptr) };
Ok(Some(bound))
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) }))

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use PyObject_HasAttrWithError on Python 3.13+

2 participants