Last active
December 20, 2016 23:36
-
-
Save gordonbrander/703bd158eb58c2b1295cd0f2df9e7c2f to your computer and use it in GitHub Desktop.
memoize.py
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 Memoize: | |
""" | |
Memoize a function based on the arguments passed in. Example:: | |
@Memoize | |
def foo(x, y): return x + y | |
""" | |
def __init__(self, f): | |
self.__function = f | |
self.__cache = {} | |
def __call__(self, *args): | |
if not args in self.__cache: | |
self.__cache[args] = self.__function(*args) | |
return self.__cache[args] | |
def invalidate(self, *args): | |
"""Invalidate the memoized value for a set of arguments.""" | |
del self.__cache[args] | |
return self |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment