Skip to content

gh-102213: Optimize the performance of __getattr__ #103761

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

Merged
merged 8 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
15 changes: 14 additions & 1 deletion Lib/test/test_descr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5004,7 +5004,7 @@ class Child(Parent):
self.assertEqual(Parent.__subclasses__(), [])

def test_attr_raise_through_property(self):
# add test case for gh-103272
# test case for gh-103272
class A:
def __getattr__(self, name):
raise ValueError("FOO")
Expand All @@ -5016,6 +5016,19 @@ def foo(self):
with self.assertRaisesRegex(ValueError, "FOO"):
A().foo

# test case for gh-103551
class B:
@property
def __getattr__(self, name):
raise ValueError("FOO")

@property
def foo(self):
raise NotImplementedError("BAR")

with self.assertRaisesRegex(NotImplementedError, "BAR"):
B().foo


class DictProxyTests(unittest.TestCase):
def setUp(self):
Expand Down
19 changes: 12 additions & 7 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -8296,17 +8296,22 @@ _Py_slot_tp_getattr_hook(PyObject *self, PyObject *name)
if (getattribute == NULL ||
(Py_IS_TYPE(getattribute, &PyWrapperDescr_Type) &&
((PyWrapperDescrObject *)getattribute)->d_wrapped ==
(void *)PyObject_GenericGetAttr))
res = PyObject_GenericGetAttr(self, name);
else {
(void *)PyObject_GenericGetAttr)) {
res = _PyObject_GenericGetAttrWithDict(self, name, NULL, 1);
/* if no error has occurred, then it must be suppressed by us */
if (res == NULL && !PyErr_Occurred()) {
res = call_attribute(self, getattr, name);
}
} else {
Py_INCREF(getattribute);
res = call_attribute(self, getattribute, name);
Py_DECREF(getattribute);
if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
res = call_attribute(self, getattr, name);
}
}
if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
res = call_attribute(self, getattr, name);
}

Py_DECREF(getattr);
return res;
}
Expand Down