Skip to content

Implement PyObject_HasOptionalAttr #117561

@MightyJosip

Description

@MightyJosip

Feature or enhancement

Proposal:

Looking at the hasattr(obj) source code I noticed it calls PyObject_GetOptionalAttr

if (PyObject_GetOptionalAttr(obj, name, &v) < 0) {
But that value (reference to attribute) is never used. My idea is to create the new function that doesn't set the reference and everything, but rather just returns 0 (if error happened or attribute doesn't exist), or 1 (if attribute exists).

2 more things.

First inside of PyObject_GetOptionalAttr function PyUnicode_Check is called more than once (both at the start of the function, and in other functions later (like in _PyObject_GenericGetAttrWithDict)

PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
So does PyUnicode_Check has performance implications, can hasattr/getattr be faster if it is called only once.

And second. Does the documentation for hasattr need improvement

cpython/Python/bltinmodule.c

Lines 1233 to 1235 in 9c1dfe2

Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
Since with introduction of PyObject_GetOptionalAttr it doesn't raise AttributeError.

This issue report is made purely as possible performance improvement question, and should be treated like that, if it is something that shouldn't be done feel free to close the issue, otherwise I would gladly try to implement the proposed change

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtopic-C-APItype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions