Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Last active June 8, 2016 11:03
Show Gist options
  • Save mbarkhau/5680003 to your computer and use it in GitHub Desktop.
Save mbarkhau/5680003 to your computer and use it in GitHub Desktop.
class Memoizer(object):
"""Memoizer for pure functions with positional hashable arguments.
Eviction from cache is done more or less at random, which
in practice is surprisingly close to a LRU strategy.
"""
def __init__(self, func, maxsize=10000):
self.func = func
self.maxsize = maxsize
self.vals = {}
self.keys = set()
def __call__(self, *args):
try:
return self.vals[args]
except KeyError:
pass
# evict
if len(self.keys) > self.maxsize:
del self.vals[self.keys.pop()]
# calc val and add to cache
val = self.func(*args)
self.vals[args] = val
self.keys.add(args)
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment