gh-124748: Fix handling kwargs in WeakKeyDictionary.update() (#124783)

This commit is contained in:
Ruslan Gilfanov 2026-02-18 18:17:08 +05:00 committed by GitHub
parent 112d8ac972
commit 1636630390
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 11 additions and 2 deletions

View file

@ -1815,6 +1815,11 @@ def test_weak_valued_union_operators(self):
def test_weak_keyed_dict_update(self):
self.check_update(weakref.WeakKeyDictionary,
{C(): 1, C(): 2, C(): 3})
d = weakref.WeakKeyDictionary()
msg = ("Keyword arguments are not supported: "
"cannot create weak reference to 'str' object")
with self.assertRaisesRegex(TypeError, msg):
d.update(k='v')
def test_weak_keyed_delitem(self):
d = weakref.WeakKeyDictionary()

View file

@ -408,14 +408,16 @@ def setdefault(self, key, default=None):
return self.data.setdefault(ref(key, self._remove),default)
def update(self, dict=None, /, **kwargs):
if kwargs:
msg = ("Keyword arguments are not supported: "
"cannot create weak reference to 'str' object")
raise TypeError(msg)
d = self.data
if dict is not None:
if not hasattr(dict, "items"):
dict = type({})(dict)
for key, value in dict.items():
d[ref(key, self._remove)] = value
if len(kwargs):
self.update(kwargs)
def __ior__(self, other):
self.update(other)

View file

@ -0,0 +1,2 @@
Improve :exc:`TypeError` error message when :meth:`!weakref.WeakKeyDictionary.update`
is used with keyword-only parameters.