Skip to content

Commit a043407

Browse files
authored
gh-142495: Make defaultdict keep existed value when racing with __missing__ (GH-142668)
1 parent 47ec96f commit a043407

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

‎Lib/test/test_defaultdict.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,5 +186,23 @@ def test_union(self):
186186
with self.assertRaises(TypeError):
187187
i |= None
188188

189+
def test_factory_conflict_with_set_value(self):
190+
key = "conflict_test"
191+
count = 0
192+
193+
def default_factory():
194+
nonlocal count
195+
count += 1
196+
local_count = count
197+
if count == 1:
198+
test_dict[key]
199+
return local_count
200+
201+
test_dict = defaultdict(default_factory)
202+
203+
self.assertEqual(count, 0)
204+
self.assertEqual(test_dict[key], 2)
205+
self.assertEqual(count, 2)
206+
189207
if __name__ == "__main__":
190208
unittest.main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:class:`collections.defaultdict` now prioritizes :meth:`~object.__setitem__`
2+
when inserting default values from ``default_factory``. This prevents race
3+
conditions where a default value would overwrite a value set before
4+
``default_factory`` returns.

‎Modules/_collectionsmodule.c‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2231,11 +2231,11 @@ defdict_missing(PyObject *op, PyObject *key)
22312231
value = _PyObject_CallNoArgs(factory);
22322232
if (value == NULL)
22332233
return value;
2234-
if (PyObject_SetItem(op, key, value) < 0) {
2235-
Py_DECREF(value);
2236-
return NULL;
2237-
}
2238-
return value;
2234+
PyObject *result = NULL;
2235+
(void)PyDict_SetDefaultRef(op, key, value, &result);
2236+
// 'result' is NULL, or a strong reference to 'value' or 'op[key]'
2237+
Py_DECREF(value);
2238+
return result;
22392239
}
22402240

22412241
static inline PyObject*

0 commit comments

Comments
 (0)