]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-39264: Fix UserDict.get() to account for __missing__() (GH-17910)
authorBar Harel <bar.harel@biocatch.com>
Tue, 10 May 2022 21:23:45 +0000 (00:23 +0300)
committerGitHub <noreply@github.com>
Tue, 10 May 2022 21:23:45 +0000 (14:23 -0700)
Here's the patch according to the discussion at the [Python-Dev mailing list](https://mail.python.org/archives/list/python-dev@python.org/thread/SDXOEMAEM6KQ3CQCJVBVRT5QNSPAVU6X/).
UserDict.get() will match dict's behavior and not call `__missing__`.

Automerge-Triggered-By: GH:rhettinger
Lib/collections/__init__.py
Lib/test/test_collections.py
Misc/NEWS.d/next/Library/2020-01-09-01-57-12.bpo-39264.GsBL9-.rst [new file with mode: 0644]

index 7af8dcd526df81fe97c2e292a3bd4ce0779918f4..58607874be93d6232607f113dbbcdf87b6323b41 100644 (file)
@@ -1132,10 +1132,17 @@ class UserDict(_collections_abc.MutableMapping):
     def __iter__(self):
         return iter(self.data)
 
-    # Modify __contains__ to work correctly when __missing__ is present
+    # Modify __contains__ and get() to work like dict
+    # does when __missing__ is present.
     def __contains__(self, key):
         return key in self.data
 
+    def get(self, key, default=None):
+        if key in self:
+            return self[key]
+        return default
+
+
     # Now, add the methods in dicts but not in MutableMapping
     def __repr__(self):
         return repr(self.data)
index fa1d0e014dee923f0f3539a31375b95db9225f1f..59b3f2ec7bfcb65e97ebf7be5c44de3eda44c03f 100644 (file)
@@ -71,6 +71,14 @@ class TestUserObjects(unittest.TestCase):
         obj[123] = "abc"
         self._copy_test(obj)
 
+    def test_dict_missing(self):
+        class A(UserDict):
+            def __missing__(self, key):
+                return 456
+        self.assertEqual(A()[123], 456)
+        # get() ignores __missing__ on dict
+        self.assertIs(A().get(123), None)
+
 
 ################################################################################
 ### ChainMap (helper class for configparser and the string module)
diff --git a/Misc/NEWS.d/next/Library/2020-01-09-01-57-12.bpo-39264.GsBL9-.rst b/Misc/NEWS.d/next/Library/2020-01-09-01-57-12.bpo-39264.GsBL9-.rst
new file mode 100644 (file)
index 0000000..5f9ffdf
--- /dev/null
@@ -0,0 +1,3 @@
+Fixed :meth:`collections.UserDict.get` to not call
+:meth:`__missing__` when a value is not found. This matches the behavior of
+:class:`dict`. Patch by Bar Harel.