Package translate :: Package misc :: Module lru

[hide private]
[frames] | no frames]

# Source Code for Module translate.misc.lru

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2009 Zuza Software Foundation
      5  #
      6  # This file is part of translate.
      7  #
      8  # This program is free software; you can redistribute it and/or modify
      9  # it under the terms of the GNU General Public License as published by
     10  # the Free Software Foundation; either version 2 of the License, or
     11  # (at your option) any later version.
     12  #
     13  # This program is distributed in the hope that it will be useful,
     14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  # GNU General Public License for more details.
     17  #
     18  # You should have received a copy of the GNU General Public License
     19  # along with this program; if not, see <http://www.gnu.org/licenses/>.
     20
     21  from collections import deque
     22  from weakref import WeakValueDictionary
     23  import gc
     24
     25 -class LRUCachingDict(WeakValueDictionary):
     26      """Caching dictionary like object that discards the least recently
     27      used objects when number of cached items exceeds maxsize.
     28
     29      cullsize is the fraction of items that will be discarded when
     30      maxsize is reached.
     31      """
     32
     33 -    def __init__(self, maxsize, cullsize=2, *args, **kwargs):
     34          self.cullsize = max(2, cullsize)
     35          self.maxsize = max(cullsize, maxsize)
     36          self.queue = deque()
     37          WeakValueDictionary.__init__(self, *args, **kwargs)
     38
     39 -    def __setitem__(self, key, value):
     40          # check boundaries to minimiza duplicate references
     41          while len(self.queue) and self.queue[0][0] == key:
     42              # item at left end of queue pop it since it'll be appended
     43              # to right
     44              self.queue.popleft()
     45
     46          while len(self.queue) and self.queue[-1][0] == key:
     47              # item at right end of queue pop it since it'll be
     48              # appended again
     49              self.queue.pop()
     50
     51          if len(self) >= self.maxsize:
     52              # maximum cache size exceeded, cull old items
     53              #
     54              # note queue is the real cache but its size is boundless
     55              # since it might have duplicate references.
     56              #
     57              # don't bother culling if queue is smaller than weakref,
     58              # this means there are too many references outside the
     59              # cache, culling won't free much memory (if any).
     60              while len(self) >= self.maxsize <= len(self.queue):
     61                  cullsize = max(int(len(self.queue) / self.cullsize), 2)
     62                  try:
     63                      for i in range(cullsize):
     64                          self.queue.popleft()
     65                  except IndexError:
     66                      # queue is empty, bail out.
     67                      #FIXME: should we force garbage collection here too?
     68                      break
     69
     70                  # call garbage collecter manually since objects
     71                  # with circular references take some time to get
     72                  # collected
     73                  for i in range(5):
     74                      if gc.collect() == 0:
     75                          break
     76          self.queue.append((key, value))
     77          WeakValueDictionary.__setitem__(self, key, value)
     78
     79
     80 -    def __getitem__(self, key):
     81          value = WeakValueDictionary.__getitem__(self, key)
     82          # check boundaries to minimiza duplicate references
     83          while len(self.queue) > 0  and self.queue[0][0] == key:
     84              # item at left end of queue pop it since it'll be appended
     85              # to right
     86              self.queue.popleft()
     87
     88          # only append if item is not at right end of queue
     89          if not (len(self.queue) and self.queue[-1][0] == key):
     90              self.queue.append((key, value))
     91
     92          return value
     93
     94 -    def __delitem__(self, key):
     95          # can't efficiently find item in queue to delete, check
     96          # boundaries. otherwise just wait till next cache purge
     97          while len(self.queue) and self.queue[0][0] == key:
     98              # item at left end of queue pop it since it'll be appended
     99              # to right
    100              self.queue.popleft()
    101
    102          while len(self.queue) and self.queue[-1][0] == key:
    103              # item at right end of queue pop it since it'll be
    104              # appended again
    105              self.queue.pop()
    106
    107          return WeakValueDictionary.__delitem__(self, key)
    108
    109 -    def clear(self):
    110          self.queue.clear()
    111          return WeakValueDictionary.clear(self)
    112
    113 -    def setdefault(self, key, default):
    114          if key not in self:
    115              self[key]=default
    116
    117          return self[key]
    118