Package genshi :: Module util :: Class LRUCache

Class LRUCache

object --+    
         |    
      dict --+
             |
            LRUCache

A dictionary-like object that stores only a certain number of items, and discards its least recently used item when full.

>>> cache = LRUCache(3)
>>> cache['A'] = 0
>>> cache['B'] = 1
>>> cache['C'] = 2
>>> len(cache)
3
>>> cache['A']
0

Adding new items to the cache does not increase its size. Instead, the least recently used item is dropped:

>>> cache['D'] = 3
>>> len(cache)
3
>>> 'B' in cache
False

Iterating over the cache returns the keys, starting with the most recently used:

>>> for key in cache:
...     print(key)
D
A
C

This code is based on the LRUCache class from myghtyutils.util, written by Mike Bayer and released under the MIT license. See:

http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py
Instance Methods
new empty dictionary

__init__(self, capacity)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
True if D has a key k, else False
__contains__(self, key)
 
__iter__(self)
iter(x)
 
__len__(self)
len(x)
 
__getitem__(self, key)
x[y]
 
__setitem__(self, key, value)
x[i]=y
 
__repr__(self)
repr(x)

Inherited from dict: __cmp__, __delitem__, __eq__, __ge__, __getattribute__, __gt__, __le__, __lt__, __ne__, __new__, __sizeof__, clear, copy, fromkeys, get, has_key, items, iteritems, iterkeys, itervalues, keys, pop, popitem, setdefault, update, values

Inherited from object: __delattr__, __format__, __reduce__, __reduce_ex__, __setattr__, __str__, __subclasshook__

Class Variables

Inherited from dict: __hash__

Properties

Inherited from object: __class__

Method Details

__init__(self, capacity)
(Constructor)

 
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
Returns:
new empty dictionary

Overrides: object.__init__
(inherited documentation)

__contains__(self, key)
(In operator)

 
Returns: True if D has a key k, else False
Overrides: dict.__contains__
(inherited documentation)

__iter__(self)

 
iter(x)
Overrides: dict.__iter__
(inherited documentation)

__len__(self)
(Length operator)

 
len(x)
Overrides: dict.__len__
(inherited documentation)

__getitem__(self, key)
(Indexing operator)

 
x[y]
Overrides: dict.__getitem__
(inherited documentation)

__setitem__(self, key, value)
(Index assignment operator)

 
x[i]=y
Overrides: dict.__setitem__
(inherited documentation)

__repr__(self)
(Representation operator)

 
repr(x)
Overrides: object.__repr__
(inherited documentation)