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
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)
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)
--- /dev/null
+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.