Skip to content

Instantly share code, notes, and snippets.

@sergejx
Created January 29, 2012 11:37
Show Gist options
  • Save sergejx/1698408 to your computer and use it in GitHub Desktop.
Save sergejx/1698408 to your computer and use it in GitHub Desktop.
Object caching metaclass
# Metaclass for caching objects based on constructor argument
class Cached(type):
def __new__(cls, name, bases, dct):
dct['_cache'] = {}
return super(Cached, cls).__new__(cls, name, bases, dct)
def __call__(cls, a):
try:
return cls._cache[a]
except KeyError:
o = super(Cached, cls).__call__(a)
cls._cache[a] = o
return o
class C(object):
__metaclass__ = Cached
def __init__(self, i):
print "C", i
self.i = i
class D(object):
__metaclass__ = Cached
def __init__(self, i):
print "D", i
self.i = i
a = C(1)
b = C(2)
c = C(1)
d = D(1)
print a is c
print a is d
print C._cache
print D._cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment