]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-141510: Fix frozendict.fromkeys() for dict subclasses (#144962)
authorVictor Stinner <vstinner@python.org>
Wed, 18 Feb 2026 17:03:04 +0000 (18:03 +0100)
committerGitHub <noreply@github.com>
Wed, 18 Feb 2026 17:03:04 +0000 (18:03 +0100)
Copy also the dictionary if a dict subclass returns a frozendict.

Lib/test/test_dict.py
Objects/dictobject.c

index 1a8ae1cd42356e834b14583c17deb743358c6bf0..71f72cb25576701e383b77616d737c6a0ff0385a 100644 (file)
@@ -1815,6 +1815,16 @@ class FrozenDictTests(unittest.TestCase):
         self.assertEqual(fd, frozendict(a=None, b=None, c=None))
         self.assertEqual(type(fd), FrozenDictSubclass2)
 
+        # Dict subclass which overrides the constructor
+        class DictSubclass(dict):
+            def __new__(self):
+                return created
+
+        fd = DictSubclass.fromkeys("abc")
+        self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))
+        self.assertEqual(type(fd), DictSubclass)
+        self.assertEqual(created, frozendict(x=1))
+
 
 if __name__ == "__main__":
     unittest.main()
index 8d3c34f87e2afe1108aa94cc0c099cbf90948fcb..af3fcca74554703ea315cb26d2dcb2229b4a3611 100644 (file)
@@ -138,6 +138,7 @@ As a consequence of this, split keys have a maximum size of 16.
 // Forward declarations
 static PyObject* frozendict_new(PyTypeObject *type, PyObject *args,
                                 PyObject *kwds);
+static PyObject* dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
 static int dict_merge(PyObject *a, PyObject *b, int override);
 
 
@@ -3305,15 +3306,18 @@ _PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
         return NULL;
     }
 
-    // If cls is a frozendict subclass with overridden constructor,
+    // If cls is a dict or frozendict subclass with overridden constructor,
     // copy the frozendict.
     PyTypeObject *cls_type = _PyType_CAST(cls);
-    if (PyFrozenDict_Check(d)
-        && PyObject_IsSubclass(cls, (PyObject*)&PyFrozenDict_Type)
-        && cls_type->tp_new != frozendict_new)
-    {
+    if (PyFrozenDict_Check(d) && cls_type->tp_new != frozendict_new) {
         // Subclass-friendly copy
-        PyObject *copy = frozendict_new(cls_type, NULL, NULL);
+        PyObject *copy;
+        if (PyObject_IsSubclass(cls, (PyObject*)&PyFrozenDict_Type)) {
+            copy = frozendict_new(cls_type, NULL, NULL);
+        }
+        else {
+            copy = dict_new(cls_type, NULL, NULL);
+        }
         if (copy == NULL) {
             Py_DECREF(d);
             return NULL;