Skip to content

Instantly share code, notes, and snippets.

@waawal
Forked from davidwtbuxton/gist:2219990
Created March 30, 2012 09:28
Show Gist options
  • Save waawal/2250315 to your computer and use it in GitHub Desktop.
Save waawal/2250315 to your computer and use it in GitHub Desktop.
Memo-ize decorator that makes classes into singleton factories
# Based on
# http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
class memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args, **kwargs):
key = (args, kwargs)
try:
return self.cache[key]
except KeyError:
value = self.func(*args, **kwargs)
self.cache[key] = value
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args, **kwargs)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
import functools
return functools.partial(self.__call__, obj)
# Decorating a class gives you a singleton!
@memoized
class Point(object):
def __init__(self, x, y, invert=False):
self.x, self.y = x, y
self.invert = invert
p1 = Point(1, 2)
p2 = Point(1, 2)
assert p1 is p2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment