mementos / mementos.py

_memento_cache = {}

def memento_factory(name, func):
    """
    Return a memoizing metaclass with the given name and key function.
    And yes that makes this a parametrized meta-metaclass, which is probably
    the most meta thing you've ever seen. If it isn't, both congratulations
    and sympathies are in order!
    """

    def call(cls, *args, **kwargs):
        key = func(cls, args, kwargs)
        try:
            return _memento_cache[key]
        except KeyError:
            instance = type.__call__(cls, *args, **kwargs)
            _memento_cache[key] = instance
            return instance
        
    mc = type(name, (type,), { '__call__': call })
    return mc

    
MementoMetaclass = memento_factory("MementoMetaclass",
                                   lambda cls, args, kwargs: (cls, ) + args + tuple(kwargs.items()) )


def with_metaclass(meta, base=object):
    """
    Create a base class with a metaclass. Compatible across Python 2 and Python
    3. Extension of the with_metaclass() found in the six module.
    """
    if not isinstance(base, tuple):
        basetuple = (base,)
    return meta("NewBase", basetuple, {})

# 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.