]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-142495: Make `defaultdict` keep existed value when racing with `__missing__` ...
authorEdward Xu <xuxiangad@gmail.com>
Tue, 16 Dec 2025 15:04:20 +0000 (23:04 +0800)
committerGitHub <noreply@github.com>
Tue, 16 Dec 2025 15:04:20 +0000 (17:04 +0200)
Lib/test/test_defaultdict.py
Misc/NEWS.d/next/Library/2025-12-13-23-26-42.gh-issue-142495.I88Uv_.rst [new file with mode: 0644]
Modules/_collectionsmodule.c

index bdbe9b81e8fb3f5a0786478ef1c01d1ee1aea291..fbd7354a915a0a001a2c7ed8a976a82315be71d3 100644 (file)
@@ -186,5 +186,23 @@ class TestDefaultDict(unittest.TestCase):
         with self.assertRaises(TypeError):
             i |= None
 
+    def test_factory_conflict_with_set_value(self):
+        key = "conflict_test"
+        count = 0
+
+        def default_factory():
+            nonlocal count
+            count += 1
+            local_count = count
+            if count == 1:
+                test_dict[key]
+            return local_count
+
+        test_dict = defaultdict(default_factory)
+
+        self.assertEqual(count, 0)
+        self.assertEqual(test_dict[key], 2)
+        self.assertEqual(count, 2)
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Misc/NEWS.d/next/Library/2025-12-13-23-26-42.gh-issue-142495.I88Uv_.rst b/Misc/NEWS.d/next/Library/2025-12-13-23-26-42.gh-issue-142495.I88Uv_.rst
new file mode 100644 (file)
index 0000000..3e1a624
--- /dev/null
@@ -0,0 +1,4 @@
+:class:`collections.defaultdict` now prioritizes :meth:`~object.__setitem__`
+when inserting default values from ``default_factory``. This prevents race
+conditions where a default value would overwrite a value set before
+``default_factory`` returns.
index 3ba48d5d9d3c6466621fa27f8c7aaf0367ae0da0..3b14a21fa8428ea2b659867d51745db5cec48e7d 100644 (file)
@@ -2231,11 +2231,11 @@ defdict_missing(PyObject *op, PyObject *key)
     value = _PyObject_CallNoArgs(factory);
     if (value == NULL)
         return value;
-    if (PyObject_SetItem(op, key, value) < 0) {
-        Py_DECREF(value);
-        return NULL;
-    }
-    return value;
+    PyObject *result = NULL;
+    (void)PyDict_SetDefaultRef(op, key, value, &result);
+    // 'result' is NULL, or a strong reference to 'value' or 'op[key]'
+    Py_DECREF(value);
+    return result;
 }
 
 static inline PyObject*