Skip to content

Commit 83464c7

Browse files
committed
gh-142085: Fix ChainMap.__ior__ to return NotImplemented for unsupported types
1 parent cfcd524 commit 83464c7

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

Lib/collections/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,10 @@ def clear(self):
11511151
self.maps[0].clear()
11521152

11531153
def __ior__(self, other):
1154-
self.maps[0].update(other)
1154+
try:
1155+
self.maps[0].update(other)
1156+
except TypeError:
1157+
return NotImplemented
11551158
return self
11561159

11571160
def __or__(self, other):

Lib/test/test_collections.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,20 @@ def __ror__(self, other):
308308
tmp = ChainMap() | SubclassRor()
309309
self.assertIs(type(tmp), SubclassRor)
310310
self.assertIs(type(tmp.maps[0]), dict)
311-
311+
312+
def test_ior_fallback(self):
313+
# Verify that __ior__ returns NotImplemented for unrecognized types,
314+
# allowing the other operand to handle the operation via __ror__.
315+
class Rescuer:
316+
def __ror__(self, other):
317+
return "fallback"
318+
319+
cm = ChainMap()
320+
# This should not raise TypeError.
321+
# Since ChainMap.__ior__ returns NotImplemented, Python calls Rescuer.__ror__,
322+
# and the result ("fallback") is assigned back to 'cm'.
323+
cm |= Rescuer()
324+
self.assertEqual(cm, "fallback")
312325

313326
################################################################################
314327
### Named Tuples

0 commit comments

Comments
 (0)