Skip to content

Commit 30a4358

Browse files
authored
bpo-39264: Fix UserDict.get() to account for __missing__() (GH-17910)
Here's the patch according to the discussion at the [Python-Dev mailing list](https://mail.python.org/archives/list/[email protected]/thread/SDXOEMAEM6KQ3CQCJVBVRT5QNSPAVU6X/). UserDict.get() will match dict's behavior and not call `__missing__`. Automerge-Triggered-By: GH:rhettinger
1 parent f481a02 commit 30a4358

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/collections/__init__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1132,10 +1132,17 @@ def __delitem__(self, key):
11321132
def __iter__(self):
11331133
return iter(self.data)
11341134

1135-
# Modify __contains__ to work correctly when __missing__ is present
1135+
# Modify __contains__ and get() to work like dict
1136+
# does when __missing__ is present.
11361137
def __contains__(self, key):
11371138
return key in self.data
11381139

1140+
def get(self, key, default=None):
1141+
if key in self:
1142+
return self[key]
1143+
return default
1144+
1145+
11391146
# Now, add the methods in dicts but not in MutableMapping
11401147
def __repr__(self):
11411148
return repr(self.data)

Lib/test/test_collections.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,14 @@ def test_dict_copy(self):
7171
obj[123] = "abc"
7272
self._copy_test(obj)
7373

74+
def test_dict_missing(self):
75+
class A(UserDict):
76+
def __missing__(self, key):
77+
return 456
78+
self.assertEqual(A()[123], 456)
79+
# get() ignores __missing__ on dict
80+
self.assertIs(A().get(123), None)
81+
7482

7583
################################################################################
7684
### ChainMap (helper class for configparser and the string module)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed :meth:`collections.UserDict.get` to not call
2+
:meth:`__missing__` when a value is not found. This matches the behavior of
3+
:class:`dict`. Patch by Bar Harel.

0 commit comments

Comments
 (0)