https://github.com/python/cpython/commit/1636630390883a5de0da26bef11da2bbf081badf
commit: 1636630390883a5de0da26bef11da2bbf081badf
branch: main
author: Ruslan Gilfanov <[email protected]>
committer: kumaraditya303 <[email protected]>
date: 2026-02-18T13:17:08Z
summary:

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

files:
A Misc/NEWS.d/next/Library/2024-09-30-15-31-59.gh-issue-124748.KYzYFp.rst
M Lib/test/test_weakref.py
M Lib/weakref.py

diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index 47f6b46061ac30..b187643e84521c 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -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()
diff --git a/Lib/weakref.py b/Lib/weakref.py
index 94e4278143c987..af7244553c908c 100644
--- a/Lib/weakref.py
+++ b/Lib/weakref.py
@@ -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)
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 00000000000000..5067db357fc577
--- /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.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to