]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Fix OrderedDict.setdefault() to work for subclasses that define __missing__().
authorRaymond Hettinger <python@rcn.com>
Fri, 31 Dec 2010 23:16:17 +0000 (23:16 +0000)
committerRaymond Hettinger <python@rcn.com>
Fri, 31 Dec 2010 23:16:17 +0000 (23:16 +0000)
Lib/collections.py
Lib/test/test_collections.py
Misc/NEWS

index 061106bd5ee9d2fcc85d35dc5a997ba8288e79b0..c69f4ca84ec049d2dd0b1da525cc8f99bbe68e6c 100644 (file)
@@ -171,7 +171,6 @@ class OrderedDict(dict, MutableMapping):
         size += sizeof(self.__root) * n         # proxy objects
         return size
 
-    setdefault = MutableMapping.setdefault
     update = MutableMapping.update
     pop = MutableMapping.pop
     keys = MutableMapping.keys
@@ -179,6 +178,13 @@ class OrderedDict(dict, MutableMapping):
     items = MutableMapping.items
     __ne__ = MutableMapping.__ne__
 
+    def setdefault(self, key, default=None):
+        'OD.setdefault(k[,d]) -> OD.get(k,d), also set OD[k]=d if k not in OD'
+        if key in self:
+            return self[key]
+        self[key] = default
+        return default
+
     @_recursive_repr()
     def __repr__(self):
         'od.__repr__() <==> repr(od)'
index 02b9dc31cea8f2f955ba334f7da2cca7feba36f5..32ce35bb1d589b2f47d942530875f81c91233d08 100644 (file)
@@ -976,6 +976,12 @@ class TestOrderedDict(unittest.TestCase):
         # make sure 'x' is added to the end
         self.assertEqual(list(od.items())[-1], ('x', 10))
 
+        # make sure setdefault still works when __missing__ is defined
+        class Missing(OrderedDict):
+            def __missing__(self, key):
+                return 0
+        self.assertEqual(Missing().setdefault(5, 9), 9)
+
     def test_reinsert(self):
         # Given insert a, insert b, delete a, re-insert a,
         # verify that a is now later than b.
index b6b968af60d6d1a7bc3e10c2fa94790892bd277e..9ddd9b3a86d1acc684e58e2132d361ba54a2999f 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -20,6 +20,9 @@ Core and Builtins
 Library
 -------
 
+- Fix collections.OrderedDict.setdefault() so that it works in
+  subclasses that define __missing__().
+
 - Issue 10786: unittest.TextTestRunner default stream no longer bound at
   import time. `sys.stderr` now looked up at instantiation time. Fix contributed
   by Mark Roddy.