[Python-checkins] gh-104078: Improve performance of PyObject_HasAttrString (#104079)

hauntsaninja webhook-mailer at python.org
Wed May 3 03:20:07 EDT 2023


https://github.com/python/cpython/commit/8d34031068ece75667260f6526d3165efe34e054
commit: 8d34031068ece75667260f6526d3165efe34e054
branch: main
author: Itamar Ostricher <itamarost at gmail.com>
committer: hauntsaninja <12621235+hauntsaninja at users.noreply.github.com>
date: 2023-05-03T00:20:00-07:00
summary:

gh-104078: Improve performance of PyObject_HasAttrString (#104079)

files:
A Misc/NEWS.d/next/Core and Builtins/2023-05-01-21-05-47.gh-issue-104078.vRaBsU.rst
M Objects/object.c

diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-05-01-21-05-47.gh-issue-104078.vRaBsU.rst b/Misc/NEWS.d/next/Core and Builtins/2023-05-01-21-05-47.gh-issue-104078.vRaBsU.rst
new file mode 100644
index 000000000000..6f24529bac3e
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2023-05-01-21-05-47.gh-issue-104078.vRaBsU.rst	
@@ -0,0 +1 @@
+Improve the performance of :c:func:`PyObject_HasAttrString`
diff --git a/Objects/object.c b/Objects/object.c
index ee8690101d3c..c6ef59281648 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -918,13 +918,24 @@ PyObject_GetAttrString(PyObject *v, const char *name)
 int
 PyObject_HasAttrString(PyObject *v, const char *name)
 {
-    PyObject *res = PyObject_GetAttrString(v, name);
-    if (res != NULL) {
-        Py_DECREF(res);
-        return 1;
+    if (Py_TYPE(v)->tp_getattr != NULL) {
+        PyObject *res = (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
+        if (res != NULL) {
+            Py_DECREF(res);
+            return 1;
+        }
+        PyErr_Clear();
+        return 0;
     }
-    PyErr_Clear();
-    return 0;
+
+    PyObject *attr_name = PyUnicode_FromString(name);
+    if (attr_name == NULL) {
+        PyErr_Clear();
+        return 0;
+    }
+    int ok = PyObject_HasAttr(v, attr_name);
+    Py_DECREF(attr_name);
+    return ok;
 }
 
 int



More information about the Python-checkins mailing list