From 378edee0a3b913d60653dc17dfe61d83405a8135 Mon Sep 17 00:00:00 2001 From: INADA Naoki Date: Tue, 16 Jan 2018 20:52:41 +0900 Subject: bpo-32544: Speed up hasattr() and getattr() (GH-5173) AttributeError was raised always when attribute is not found. This commit skip raising AttributeError when `tp_getattro` is `PyObject_GenericGetAttr`. It makes hasattr() and getattr() about 4x faster when attribute is not found. --- Python/bltinmodule.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'Python/bltinmodule.c') diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index e702f7c6e9..844548f75f 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1126,13 +1126,15 @@ builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs) "getattr(): attribute name must be string"); return NULL; } - result = PyObject_GetAttr(v, name); - if (result == NULL && dflt != NULL && - PyErr_ExceptionMatches(PyExc_AttributeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - result = dflt; + if (dflt != NULL) { + result = _PyObject_GetAttrWithoutError(v, name); + if (result == NULL && !PyErr_Occurred()) { + Py_INCREF(dflt); + return dflt; + } + } + else { + result = PyObject_GetAttr(v, name); } return result; } @@ -1189,10 +1191,9 @@ builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name) "hasattr(): attribute name must be string"); return NULL; } - v = PyObject_GetAttr(obj, name); + v = _PyObject_GetAttrWithoutError(obj, name); if (v == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); + if (!PyErr_Occurred()) { Py_RETURN_FALSE; } return NULL; -- cgit v1.2.1