Source

bx-python / lib / bx_extras / lrucache.py

Diff from to

lib/bx_extras/lrucache.py

 """
 
 from __future__ import generators
+
+# TODO: Remove this in favor of functools.lru_cache
+
 import time
 from heapq import heappush, heappop, heapify
+from functools import total_ordering
 
 __version__ = "0.2"
 __all__ = ['CacheKeyError', 'LRUCache', 'DEFAULT_SIZE']
 
 class CacheKeyError(KeyError):
     """Error raised when cache requests fail
-    
+
     When a cache record is accessed which no longer exists (or never did),
     this error is raised. To avoid it, you may want to check for the existence
     of a cache record before reading or deleting it."""
 
 class LRUCache(object):
     """Least-Recently-Used (LRU) cache.
-    
+
     Instances of this class provide a least-recently-used (LRU) cache. They
     emulate a Python mapping type. You can use an LRU cache more or less like
     a Python dictionary, with the exception that objects you put into the
     cache may be discarded before you take them out.
-    
+
     Some example usage::
-	
+
     cache = LRUCache(32) # new cache
     cache['foo'] = get_file_contents('foo') # or whatever
-	
+
     if 'foo' in cache: # if it's still in cache...
 	    # use cached version
         contents = cache['foo']
         cache['foo'] = contents
 
     print cache.size # Maximum size
-	
+
     print len(cache) # 0 <= len(cache) <= cache.size
-	
+
     cache.size = 10 # Auto-shrink on size assignment
-	
+
     for i in range(50): # note: larger than cache size
         cache[i] = i
-	    
+
     if 0 not in cache: print 'Zero was discarded.'
 
     if 42 in cache:
     for j in cache:   # iterate (in LRU order)
         print j, cache[j] # iterator produces keys, not values
     """
-    
+
+    @total_ordering
     class __Node(object):
         """Record of a cached value. Not for public consumption."""
-        
+
         def __init__(self, key, obj, timestamp):
             object.__init__(self)
             self.key = key
             self.obj = obj
             self.atime = timestamp
             self.mtime = self.atime
-	    
-        def __cmp__(self, other):
-            return cmp(self.atime, other.atime)
+
+        def __lt__(self, other):
+            return self.atime < other.atime
+
+        def __eq__(self, other):
+            return self.atime == other.atime
 
         def __repr__(self):
             return "<%s %s => %s (%s)>" % \
-                   (self.__class__, self.key, self.obj, \
+                   (self.__class__, self.key, self.obj,
                     time.asctime(time.localtime(self.atime)))
 
     def __init__(self, size=DEFAULT_SIZE):
             raise ValueError, size
         elif type(size) is not type(0):
             raise TypeError, size
-        object.__init__(self)	
+        object.__init__(self)
         self.__heap = []
         self.__dict = {}
         self.size = size
         """Maximum size of the cache.
         If more than 'size' elements are added to the cache,
         the least-recently-used ones will be discarded."""
-	
+
     def __len__(self):
         return len(self.__heap)
-    
+
     def __contains__(self, key):
         return self.__dict.has_key(key)
-    
+
     def __setitem__(self, key, obj):
         if self.__dict.has_key(key):
             node = self.__dict[key]
             node = self.__Node(key, obj, time.time())
             self.__dict[key] = node
             heappush(self.__heap, node)
-	
+
     def __getitem__(self, key):
         if not self.__dict.has_key(key):
             raise CacheKeyError(key)
             node.atime = time.time()
             heapify(self.__heap)
             return node.obj
-	
+
     def __delitem__(self, key):
         if not self.__dict.has_key(key):
             raise CacheKeyError(key)
             while len(self.__heap) > value:
                 lru = heappop(self.__heap)
                 del self.__dict[lru.key]
-	    
+
     def __repr__(self):
         return "<%s (%d elements)>" % (str(self.__class__), len(self.__heap))
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.