Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,10 @@ def clear(self):
self.maps[0].clear()

def __ior__(self, other):
self.maps[0].update(other)
try:
self.maps[0].update(other)
except TypeError:
return NotImplemented
Comment thread
ChuheLin marked this conversation as resolved.
return self

def __or__(self, other):
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,19 @@ def __ror__(self, other):
self.assertIs(type(tmp), SubclassRor)
self.assertIs(type(tmp.maps[0]), dict)

def test_ior_fallback(self):
# Verify that __ior__ returns NotImplemented for unrecognized types,
# allowing the other operand to handle the operation via __ror__.
class Rescuer:
def __ror__(self, other):
return "fallback"

cm = ChainMap()
# This should not raise TypeError.
# Since ChainMap.__ior__ returns NotImplemented, Python calls Rescuer.__ror__,
# and the result ("fallback") is assigned back to 'cm'.
cm |= Rescuer()
self.assertEqual(cm, "fallback")

################################################################################
### Named Tuples
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :meth:`~collections.ChainMap.__ior__` to return :const:`NotImplemented` instead of raising :exc:`TypeError` for unsupported types.
Loading