Ignore:
Timestamp:
Jul 20, 2009, 1:04:55 PM (12 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Convert:
svn:778c30c8-61e0-0310-89d4-fe2f97a467b2/trunk@882
Message:
Support for limit case of zero size.

Removed type check for constructor size argument. Provided a
more meaningful error message if the size is negative. Added
range check upon resizing.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • lrucache.py

    r789 r812  
    4545# the suffix after the hyphen denotes modifications by the
    4646#  ftputil project with respect to the original version
    47 __version__ = "0.2-1"
     47__version__ = "0.2-2"
    4848__all__ = ['CacheKeyError', 'LRUCache', 'DEFAULT_SIZE']
    4949__docformat__ = 'reStructuredText en'
     
    121121    def __init__(self, size=DEFAULT_SIZE):
    122122        # Check arguments
    123         if size <= 0:
    124             raise ValueError, size
    125         elif type(size) is not type(0):
    126             raise TypeError, size
     123        if size < 0:
     124            raise ValueError("cache size (%d) mustn't be negative" % size)
    127125        object.__init__(self)
    128126        self.__heap = []
     
    136134    def _sort_key(self):
    137135        """Return a new integer value upon every call.
    138        
     136
    139137        Cache nodes need a monotonically increasing time indicator.
    140138        time.time() and time.clock() don't guarantee this in a
     
    151149
    152150    def __setitem__(self, key, obj):
     151        if self.size == 0:
     152            # can't store anything
     153            return
    153154        if self.__dict.has_key(key):
    154155            node = self.__dict[key]
     
    160161            heapify(self.__heap)
    161162        else:
    162             # size may have been reset, so we loop
    163             while len(self.__heap) >= self.size:
     163            # size of the heap can be at most the value of
     164            #  self.size because __setattr__ decreases the cache
     165            #  size if the new size value is smaller; so we don't
     166            #  need a loop _here_
     167            if len(self.__heap) == self.size:
    164168                lru = heappop(self.__heap)
    165169                del self.__dict[lru.key]
     
    200204        # automagically shrink heap on resize
    201205        if name == 'size':
     206            if value < 0:
     207                raise ValueError("cache size (%d) mustn't be negative" % size)
    202208            while len(self.__heap) > value:
    203209                lru = heappop(self.__heap)
Note: See TracChangeset for help on using the changeset viewer.