Changeset 787:0b29d67d4210


Ignore:
Timestamp:
May 3, 2009, 7:54:37 PM (12 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Convert:
svn:778c30c8-61e0-0310-89d4-fe2f97a467b2/trunk@855
Message:
Use a counter instead of `time.time()` to determine the heap order.
This fixes bug #32.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • lrucache.py

    r786 r787  
    4343from heapq import heappush, heappop, heapify
    4444
    45 __version__ = "0.2"
     45__version__ = "0.2.1"
    4646__all__ = ['CacheKeyError', 'LRUCache', 'DEFAULT_SIZE']
    4747__docformat__ = 'reStructuredText en'
     
    101101        """Record of a cached value. Not for public consumption."""
    102102
    103         def __init__(self, key, obj, timestamp):
     103        def __init__(self, key, obj, timestamp, sort_key):
    104104            object.__init__(self)
    105105            self.key = key
     
    107107            self.atime = timestamp
    108108            self.mtime = self.atime
     109            self._sort_key = sort_key
    109110
    110111        def __cmp__(self, other):
    111             return cmp(self.atime, other.atime)
     112            return cmp(self._sort_key, other._sort_key)
    112113
    113114        def __repr__(self):
     
    125126        self.__heap = []
    126127        self.__dict = {}
    127         self.size = size
    128128        """Maximum size of the cache.
    129129        If more than 'size' elements are added to the cache,
    130130        the least-recently-used ones will be discarded."""
     131        self.size = size
     132        self.__counter = 0
     133
     134    def _sort_key(self):
     135        """Return a new integer value upon every call."""
     136        self.__counter += 1
     137        return self.__counter
    131138
    132139    def __len__(self):
     
    139146        if self.__dict.has_key(key):
    140147            node = self.__dict[key]
     148            # update node object in-place
    141149            node.obj = obj
    142150            node.atime = time.time()
    143151            node.mtime = node.atime
     152            node._sort_key = self._sort_key()
    144153            heapify(self.__heap)
    145154        else:
     
    148157                lru = heappop(self.__heap)
    149158                del self.__dict[lru.key]
    150             node = self.__Node(key, obj, time.time())
     159            node = self.__Node(key, obj, time.time(), self._sort_key())
    151160            self.__dict[key] = node
    152161            heappush(self.__heap, node)
     
    157166        else:
    158167            node = self.__dict[key]
     168            # update node object in-place
    159169            node.atime = time.time()
     170            node._sort_key = self._sort_key()
    160171            heapify(self.__heap)
    161172            return node.obj
Note: See TracChangeset for help on using the changeset viewer.