summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorMark Shannon <mark@hotpy.org>2021-08-04 15:41:14 (GMT)
committerGitHub <noreply@github.com>2021-08-04 15:41:14 (GMT)
commitcee67fa66129b5d1db5c8aa3884338f82f0da3de (patch)
tree079f04f5ba63c5cbd2133c7ada636d28e117ff18 /Objects
parentc83919bd635f4433f1c6ae8504996a9fe3c215e5 (diff)
downloadcpython-cee67fa66129b5d1db5c8aa3884338f82f0da3de.zip
cpython-cee67fa66129b5d1db5c8aa3884338f82f0da3de.tar.gz
cpython-cee67fa66129b5d1db5c8aa3884338f82f0da3de.tar.bz2
bpo-44821: Eagerly assign __dict__ for new objects. (GH-27589)
Diffstat (limited to 'Objects')
-rw-r--r--Objects/dictobject.c31
-rw-r--r--Objects/typeobject.c10
2 files changed, 37 insertions, 4 deletions
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index 5fb9d01..5ad630f 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -4866,19 +4866,44 @@ _PyDict_NewKeysForClass(void)
#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
+int
+_PyObject_InitializeDict(PyObject *obj)
+{
+ PyObject **dictptr = _PyObject_GetDictPtr(obj);
+ if (dictptr == NULL) {
+ return 0;
+ }
+ assert(*dictptr == NULL);
+ PyTypeObject *tp = Py_TYPE(obj);
+ PyObject *dict;
+ if (_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
+ dictkeys_incref(CACHED_KEYS(tp));
+ dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
+ }
+ else {
+ dict = PyDict_New();
+ }
+ if (dict == NULL) {
+ return -1;
+ }
+ *dictptr = dict;
+ return 0;
+}
+
+
PyObject *
PyObject_GenericGetDict(PyObject *obj, void *context)
{
- PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
+ PyObject **dictptr = _PyObject_GetDictPtr(obj);
if (dictptr == NULL) {
PyErr_SetString(PyExc_AttributeError,
"This object has no __dict__");
return NULL;
}
- dict = *dictptr;
+ PyObject *dict = *dictptr;
if (dict == NULL) {
PyTypeObject *tp = Py_TYPE(obj);
- if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
+ if (_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
dictkeys_incref(CACHED_KEYS(tp));
*dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
}
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 2240f78..7ae50c4 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -4505,7 +4505,15 @@ object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Py_DECREF(joined);
return NULL;
}
- return type->tp_alloc(type, 0);
+ PyObject *obj = type->tp_alloc(type, 0);
+ if (obj == NULL) {
+ return NULL;
+ }
+ if (_PyObject_InitializeDict(obj)) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ return obj;
}
static void