Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active December 20, 2016 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/703bd158eb58c2b1295cd0f2df9e7c2f to your computer and use it in GitHub Desktop.
Save gordonbrander/703bd158eb58c2b1295cd0f2df9e7c2f to your computer and use it in GitHub Desktop.
memoize.py
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