]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-124748: Fix handling kwargs in `WeakKeyDictionary.update()` (#124783)
authorRuslan Gilfanov <ri.gilfanov@yandex.ru>
Wed, 18 Feb 2026 13:17:08 +0000 (18:17 +0500)
committerGitHub <noreply@github.com>
Wed, 18 Feb 2026 13:17:08 +0000 (13:17 +0000)
Lib/test/test_weakref.py
Lib/weakref.py
Misc/NEWS.d/next/Library/2024-09-30-15-31-59.gh-issue-124748.KYzYFp.rst [new file with mode: 0644]

index 47f6b46061ac3045a5242714437621bb8b97f85a..b187643e84521cc8e6d8c790a958dcb273670eb6 100644 (file)
@@ -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()
index 94e4278143c9878a82aa1c397267309ea0ea16cc..af7244553c908ce4e290cfade617828a66bf358f 100644 (file)
@@ -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 (file)
index 0000000..5067db3
--- /dev/null
@@ -0,0 +1,2 @@
+Improve :exc:`TypeError` error message when :meth:`!weakref.WeakKeyDictionary.update`\r
+is used with keyword-only parameters.\r