Skip to content

Commit f353473

Browse files
committed
Added Union operators to WeakKeyDictionary
Added `_ior_`, `__or__`, and `__ror__` methods to WeakKeyDictionary and added corresponding tests to test_weakref.py.
1 parent 384f3c5 commit f353473

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Lib/test/test_weakref.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1624,6 +1624,21 @@ def test_weak_keyed_delitem(self):
16241624
self.assertEqual(len(d), 1)
16251625
self.assertEqual(list(d.keys()), [o2])
16261626

1627+
def test_weak_keyed_union_operators(self):
1628+
class C: pass
1629+
c1 = C()
1630+
c2 = C()
1631+
c3 = C()
1632+
1633+
wvd1 = weakref.WeakKeyDictionary({c1: '1', c2: '2'})
1634+
wvd2 = weakref.WeakKeyDictionary({c3: '3', c1: '4'})
1635+
1636+
wvd3 = wvd1 | wvd2
1637+
self.assertEqual(dict(wvd3), dict(wvd1) | dict(wvd2))
1638+
1639+
wvd1 |= wvd2
1640+
self.assertEqual(wvd1, wvd3)
1641+
16271642
def test_weak_valued_delitem(self):
16281643
d = weakref.WeakValueDictionary()
16291644
o1 = Object('1')

Lib/weakref.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,20 @@ def update(self, dict=None, /, **kwargs):
488488
if len(kwargs):
489489
self.update(kwargs)
490490

491+
def __ior__(self, other):
492+
self.update(other)
493+
return self
494+
495+
def __or__(self, other):
496+
c = self.copy()
497+
c.update(other)
498+
return c
499+
500+
def __ror__(self, other):
501+
c = other.copy()
502+
c.update(self)
503+
return c
504+
491505

492506
class finalize:
493507
"""Class for finalization of weakrefable objects

0 commit comments

Comments
 (0)