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