Browse Source

Fix LRUCache.update for Python 3.5

Python 3.5's OrderedDict does not allow mutation while it is being
iterated over. This breaks "update" if it is called with a dict
larger than the maximum size.

This commit changes the code to a version that does not iterate over
the dict, and should also be a little bit faster.

Closes #2897
Dennis Brakhane 9 years ago
parent
commit
0cc9a4fd14
3 changed files with 10 additions and 4 deletions
  1. 2 0
      CONTRIBUTORS.txt
  2. 5 0
      celery/tests/utils/test_functional.py
  3. 3 4
      celery/utils/functional.py

+ 2 - 0
CONTRIBUTORS.txt

@@ -195,3 +195,5 @@ Piotr Maślanka, 2015/08/24
 Gerald Manipon, 2015/10/19
 Krzysztof Bujniewicz, 2015/10/21
 Sukrit Khera, 2015/10/26
+Dave Smith, 2015/10/27
+Dennis Brakhane, 2015/10/30

+ 5 - 0
celery/tests/utils/test_functional.py

@@ -62,6 +62,11 @@ class test_LRUCache(Case):
         x[7] = 7
         self.assertEqual(list(x.keys()), [3, 6, 7])
 
+    def test_update_larger_than_cache_size(self):
+        x = LRUCache(2)
+        x.update({x: x for x in range(100)})
+        self.assertEqual(list(x.keys()), [98, 99])
+
     def assertSafeIter(self, method, interval=0.01, size=10000):
         from threading import Thread, Event
         from time import sleep

+ 3 - 4
celery/utils/functional.py

@@ -18,7 +18,7 @@ from kombu.utils import cached_property
 from kombu.utils.functional import lazy, maybe_evaluate, is_list, maybe_list
 from kombu.utils.compat import OrderedDict
 
-from celery.five import UserDict, UserList, items, keys
+from celery.five import UserDict, UserList, items, keys, range
 
 __all__ = ['LRUCache', 'is_list', 'maybe_list', 'memoize', 'mlazy', 'noop',
            'first', 'firstmethod', 'chunks', 'padlist', 'mattrgetter', 'uniq',
@@ -64,9 +64,8 @@ class LRUCache(UserDict):
             data.update(*args, **kwargs)
             if limit and len(data) > limit:
                 # pop additional items in case limit exceeded
-                # negative overflow will lead to an empty list
-                for item in islice(iter(data), len(data) - limit):
-                    data.pop(item)
+                for _ in range(len(data) - limit):
+                    data.popitem(last=False)
 
     def popitem(self, last=True, _needs_lock=IS_PYPY):
         if not _needs_lock: