diff --git a/Lib/collections/_defaultdict.py b/Lib/collections/_defaultdict.py index b9c6c4961..cb9d403c8 100644 --- a/Lib/collections/_defaultdict.py +++ b/Lib/collections/_defaultdict.py @@ -17,6 +17,10 @@ class defaultdict(dict): val = self.default_factory() else: raise KeyError(key) + # CPython parity: a recursive __missing__ via factory() may have + # already populated key; preserve that value instead of overwriting. + if key in self: + return self[key] self[key] = val return val diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py index f10603fb4..fbd7354a9 100644 --- a/Lib/test/test_defaultdict.py +++ b/Lib/test/test_defaultdict.py @@ -186,7 +186,6 @@ class TestDefaultDict(unittest.TestCase): with self.assertRaises(TypeError): i |= None - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 1 != 2 def test_factory_conflict_with_set_value(self): key = "conflict_test" count = 0