
from __future__ import absolute_import
from __future__ import division

import functools


class memoized(object):
    def __init__(self, func):
        self.func = func
        self.cache = {}
        functools.update_wrapper(self, func)

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            value = self.func(*args)
            self.cache[args] = value
            return value

    def invalidate(self):
        self.cache.clear()

    def __get__(self, obj, objtype):
        """Support instance methods."""
        wrapper = functools.partial(self.__call__, obj)
        wrapper.invalidate = self.cache.clear
        return wrapper
