Source

simplere / mementossre.py

Full commit
class MementoMetaclassSRE(type):
    """
    Classes that use this caching metaclass will have their instances
    automatically cached based on instantiation-time arguments (i.e. to __init__).
    Super-useful for not repetitively creating expensive-to-create objects.
    
    See http://code.activestate.com/recipes/286132-memento-design-pattern-in-python/
    """
    cache = {}

    def __call__(self, *args, **kwargs):
        print "MementoMetaclassSRE.__call__()"
        key = (self, ) + args + tuple(kwargs.items())
        try:
            return self.cache[key]
        except KeyError:
            instance = type.__call__(self, *args, **kwargs)
            self.cache[key] = instance
            return instance

# Looking to possibility of creating a parametrized metaclass, metaclass
# factory, or similar mecahnism to be able to configure MementoMetaclass on the
# fly. This would provide a mechanism for MementoMetaclass users to stipulate
# what parameters are used as the object-identifying key (currently: all of
# them, in exactly the call signature). Not ready to pull the trigger on that,
# however. Metaclasses are a bit tricky, and must be "done right." 

# Some reading:
# http://bytes.com/topic/python/answers/40084-parameterized-metaclass-metametaclass
# http://www.acooke.org/cute/PythonMeta0.html
# http://www.python.org/dev/peps/pep-3115/