cstrap
4/30/2015 - 7:54 AM

Memoize with Python decorator

Memoize with Python decorator

# -*- coding: utf-8 -*-
from functools import wraps


def memoize(obj):
    """
    From Python Decorator Library
    """
    cache = obj.cache = {}

    @wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        return cache[key]
    return memoizer


def memoize_method(obj):
    """
    memoize class method adding a property to the class instance
    """
    @wraps(obj)
    def memoizer(*args, **kwargs):
        instance = args[0]
        cache_method = '_{}_cache'.format(obj.__name__)
        key = args[1:] + tuple(sorted(kwargs.items()))

        if not hasattr(instance, cache_method):
            setattr(instance, cache_method, {})
        _cache = getattr(instance, cache_method)

        if key not in _cache:
            _cache[key] = obj(*args, **kwargs)
        return _cache[key]

    return memoizer