translate.misc.lru

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 cull(self):
     40          """free memory by deleting old items from cache"""
     41          # maximum cache size exceeded, cull old items
     42          #
     43          # note queue is the real cache but its size is boundless
     44          # since it might have duplicate references.
     45          #
     46          # don't bother culling if queue is smaller than weakref,
     47          # this means there are too many references outside the
     48          # cache, culling won't free much memory (if any).
     49          while len(self) >= self.maxsize <= len(self.queue):
     50              cullsize = max(int(len(self.queue) / self.cullsize), 2)
     51              try:
     52                  for i in range(cullsize):
     53                      self.queue.popleft()
     54              except IndexError:
     55                  # queue is empty, bail out.
     56                  #FIXME: should we force garbage collection here too?
     57                  break
     58
     59              # call garbage collecter manually since objects
     60              # with circular references take some time to get
     61              # collected
     62              for i in xrange(5):
     63                  gc.collect()
     64
     65 -    def __setitem__(self, key, value):
     66          # check boundaries to minimiza duplicate references
     67          while len(self.queue) and self.queue[0][0] == key:
     68              # item at left end of queue pop it since it'll be appended
     69              # to right
     70              self.queue.popleft()
     71
     72          while len(self.queue) and self.queue[-1][0] == key:
     73              # item at right end of queue pop it since it'll be
     74              # appended again
     75              self.queue.pop()
     76
     77          if len(self) >= self.maxsize:
     78              self.cull()
     79
     80          self.queue.append((key, value))
     81          WeakValueDictionary.__setitem__(self, key, value)
     82
     83 -    def __getitem__(self, key):
     84          value = WeakValueDictionary.__getitem__(self, key)
     85          # check boundaries to minimiza duplicate references
     86          while len(self.queue) > 0  and self.queue[0][0] == key:
     87              # item at left end of queue pop it since it'll be appended
     88              # to right
     89              self.queue.popleft()
     90
     91          # only append if item is not at right end of queue
     92          if not (len(self.queue) and self.queue[-1][0] == key):
     93              self.queue.append((key, value))
     94
     95          return value
     96
     97 -    def __delitem__(self, key):
     98          # can't efficiently find item in queue to delete, check
     99          # boundaries. otherwise just wait till next cache purge
    100          while len(self.queue) and self.queue[0][0] == key:
    101              # item at left end of queue pop it since it'll be appended
    102              # to right
    103              self.queue.popleft()
    104
    105          while len(self.queue) and self.queue[-1][0] == key:
    106              # item at right end of queue pop it since it'll be
    107              # appended again
    108              self.queue.pop()
    109
    110          return WeakValueDictionary.__delitem__(self, key)
    111
    112 -    def clear(self):
    113          self.queue.clear()
    114          return WeakValueDictionary.clear(self)
    115
    116 -    def setdefault(self, key, default):
    117          if key not in self:
    118              self[key] = default
    119
    120          return self[key]
    121