LRU_Cache

class ssapy.utils.LRU_Cache(user_function, maxsize=1024)[source][source]

Bases: object

Simplified Least Recently Used Cache.

Mostly stolen from http://code.activestate.com/recipes/577970-simplified-lru-cache/, but added a method for dynamic resizing. The least recently used cached item is overwritten on a cache miss.

Parameters:
  • user_function – A python function to cache.

  • maxsize – Maximum number of inputs to cache. [Default: 1024]

Example:

>>> def slow_function(*args) # A slow-to-evaluate python function
>>>    ...
>>>
>>> v1 = slow_function(*k1)  # Calling function is slow
>>> v1 = slow_function(*k1)  # Calling again with same args is still slow
>>> cache = LRU_Cache(slow_function)
>>> v1 = cache(*k1)  # Returns slow_function(*k1), slowly the first time
>>> v1 = cache(*k1)  # Returns slow_function(*k1) again, but fast this time.

Methods Summary

__call__(*key)

Call self as a function.

resize(maxsize)

Resize the cache.

Methods Documentation

__call__(*key)[source][source]

Call self as a function.

resize(maxsize)[source][source]

Resize the cache.

Increasing the size of the cache is non-destructive, i.e., previously cached inputs remain in the cache. Decreasing the size of the cache will necessarily remove items from the cache if the cache is already filled. Items are removed in least recently used order.

Parameters:

maxsize – The new maximum number of inputs to cache.