Last active
June 8, 2016 11:03
-
-
Save mbarkhau/5680003 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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