mementos / mementos.py

class MementoMetaclass(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):
        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/
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.