Skip to content

gh-92216: improve performance of hasattr for type objects #99977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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 Include/internal/pycore_typeobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ extern static_builtin_state * _PyStaticType_GetState(PyTypeObject *);
extern void _PyStaticType_ClearWeakRefs(PyTypeObject *type);
extern void _PyStaticType_Dealloc(PyTypeObject *type);

PyObject *_Py_type_getattro(PyTypeObject *type, PyObject *name, int supress);

PyObject *_Py_slot_tp_getattro(PyObject *self, PyObject *name);
PyObject *_Py_slot_tp_getattr_hook(PyObject *self, PyObject *name);
Expand Down
14 changes: 14 additions & 0 deletions Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,20 @@ int
PyObject_HasAttr(PyObject *v, PyObject *name)
{
PyObject *res;

if (Py_IS_TYPE(v, &PyType_Type)) // exact type object
{
PyObject *result = _Py_type_getattro((PyTypeObject*)v, name, 1);
if (result != NULL) {
return 1;
}
if (PyErr_Occurred()) {
PyErr_Clear();
return 0;
}
return 0;
}

if (_PyObject_LookupAttr(v, name, &res) < 0) {
PyErr_Clear();
return 0;
Expand Down
14 changes: 12 additions & 2 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -4237,8 +4237,8 @@ is_dunder_name(PyObject *name)

/* This is similar to PyObject_GenericGetAttr(),
but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
static PyObject *
type_getattro(PyTypeObject *type, PyObject *name)
PyObject *
_Py_type_getattro(PyTypeObject *type, PyObject *name, int suppress_exception)
{
PyTypeObject *metatype = Py_TYPE(type);
PyObject *meta_attribute, *attribute;
Expand Down Expand Up @@ -4318,12 +4318,22 @@ type_getattro(PyTypeObject *type, PyObject *name)
}

/* Give up */
if (!suppress_exception) {
PyErr_Format(PyExc_AttributeError,
"type object '%.50s' has no attribute '%U'",
type->tp_name, name);
}
return NULL;
}

/* This is similar to PyObject_GenericGetAttr(),
but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
static PyObject *
type_getattro(PyTypeObject *type, PyObject *name)
{
return _Py_type_getattro(type, name, 0);
}

static int
type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
Expand Down