Skip to content

Commit 1636630

Browse files
authored
gh-124748: Fix handling kwargs in WeakKeyDictionary.update() (#124783)
1 parent 112d8ac commit 1636630

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

Lib/test/test_weakref.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1815,6 +1815,11 @@ def test_weak_valued_union_operators(self):
18151815
def test_weak_keyed_dict_update(self):
18161816
self.check_update(weakref.WeakKeyDictionary,
18171817
{C(): 1, C(): 2, C(): 3})
1818+
d = weakref.WeakKeyDictionary()
1819+
msg = ("Keyword arguments are not supported: "
1820+
"cannot create weak reference to 'str' object")
1821+
with self.assertRaisesRegex(TypeError, msg):
1822+
d.update(k='v')
18181823

18191824
def test_weak_keyed_delitem(self):
18201825
d = weakref.WeakKeyDictionary()

Lib/weakref.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,14 +408,16 @@ def setdefault(self, key, default=None):
408408
return self.data.setdefault(ref(key, self._remove),default)
409409

410410
def update(self, dict=None, /, **kwargs):
411+
if kwargs:
412+
msg = ("Keyword arguments are not supported: "
413+
"cannot create weak reference to 'str' object")
414+
raise TypeError(msg)
411415
d = self.data
412416
if dict is not None:
413417
if not hasattr(dict, "items"):
414418
dict = type({})(dict)
415419
for key, value in dict.items():
416420
d[ref(key, self._remove)] = value
417-
if len(kwargs):
418-
self.update(kwargs)
419421

420422
def __ior__(self, other):
421423
self.update(other)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`TypeError` error message when :meth:`!weakref.WeakKeyDictionary.update`
2+
is used with keyword-only parameters.

0 commit comments

Comments
 (0)