From: Ruslan Gilfanov Date: Wed, 18 Feb 2026 13:17:08 +0000 (+0500) Subject: gh-124748: Fix handling kwargs in `WeakKeyDictionary.update()` (#124783) X-Git-Tag: v3.15.0a7~241 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=1636630390883a5de0da26bef11da2bbf081badf;p=thirdparty%2FPython%2Fcpython.git gh-124748: Fix handling kwargs in `WeakKeyDictionary.update()` (#124783) --- diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index 47f6b46061ac..b187643e8452 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -1815,6 +1815,11 @@ class MappingTestCase(TestBase): 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() diff --git a/Lib/weakref.py b/Lib/weakref.py index 94e4278143c9..af7244553c90 100644 --- a/Lib/weakref.py +++ b/Lib/weakref.py @@ -408,14 +408,16 @@ class WeakKeyDictionary(_collections_abc.MutableMapping): 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) diff --git a/Misc/NEWS.d/next/Library/2024-09-30-15-31-59.gh-issue-124748.KYzYFp.rst b/Misc/NEWS.d/next/Library/2024-09-30-15-31-59.gh-issue-124748.KYzYFp.rst new file mode 100644 index 000000000000..5067db357fc5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-30-15-31-59.gh-issue-124748.KYzYFp.rst @@ -0,0 +1,2 @@ +Improve :exc:`TypeError` error message when :meth:`!weakref.WeakKeyDictionary.update` +is used with keyword-only parameters.