Patchwork [7,of,8] util: implement pop() on lrucachedict

login
register
mail settings
Submitter Yuya Nishihara
Date Dec. 6, 2018, 12:45 p.m.
Message ID <d5e7ded8150f66f89b5b.1544100314@mimosa>
Download mbox | patch
Permalink /patch/37029/
State Accepted
Headers show

Comments

Yuya Nishihara - Dec. 6, 2018, 12:45 p.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1541318225 -32400
#      Sun Nov 04 16:57:05 2018 +0900
# Node ID d5e7ded8150f66f89b5b6ed0a0c49ea38018982e
# Parent  2d23efc7274a923baffe9d0dc46709d651c468b4
util: implement pop() on lrucachedict

This moves __delitem__() to pop() as the requirement is pretty much the same,
and reimplement __delitem__() by using pop().

Patch

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1320,7 +1320,16 @@  class lrucachedict(object):
         self.insert(k, v)
 
     def __delitem__(self, k):
-        node = self._cache.pop(k)
+        self.pop(k)
+
+    def pop(self, k, default=_notset):
+        try:
+            node = self._cache.pop(k)
+        except KeyError:
+            if default is _notset:
+                raise
+            return default
+        value = node.value
         self.totalcost -= node.cost
         node.markempty()
 
@@ -1329,6 +1338,8 @@  class lrucachedict(object):
         self._movetohead(node)
         self._head = node.next
 
+        return value
+
     # Additional dict methods.
 
     def get(self, k, default=None):
diff --git a/tests/test-lrucachedict.py b/tests/test-lrucachedict.py
--- a/tests/test-lrucachedict.py
+++ b/tests/test-lrucachedict.py
@@ -94,6 +94,21 @@  class testlrucachedict(unittest.TestCase
         self.assertEqual(d.peek('a'), 'va')
         self.assertEqual(list(d), ['c', 'b', 'a'])
 
+    def testpop(self):
+        d = util.lrucachedict(4)
+        d['a'] = 'va'
+        d['b'] = 'vb'
+        d['c'] = 'vc'
+
+        with self.assertRaises(KeyError):
+            d.pop('missing')
+        self.assertEqual(list(d), ['c', 'b', 'a'])
+        self.assertIsNone(d.pop('missing', None))
+        self.assertEqual(list(d), ['c', 'b', 'a'])
+
+        self.assertEqual(d.pop('b'), 'vb')
+        self.assertEqual(list(d), ['c', 'a'])
+
     def testcopypartial(self):
         d = util.lrucachedict(4)
         d.insert('a', 'va', cost=4)