view src/ltpdarepo/memoize.py @ 213:3d524d31d1c2

Move setup.py to better location.
author Daniele Nicolodi <daniele@grinta.net>
date Fri, 18 Nov 2011 01:49:52 +0100
parents fbab144c296c
children
line wrap: on
line source

# Copyright 2011 Daniele Nicolodi <nicolodi@science.unitn.it>
#
# This software may be used and distributed according to the terms of
# the GNU Affero General Public License version 3 or any later version.

import functools

class memoize(object):
    """Decorator that caches a function's return value each time it is called.
    """
    def __init__(self, func):
       self.func = func
       self.cache = {}
       
    def __call__(self, *args):
       try:
          return self.cache[args]
       except KeyError:
          value = self.func(*args)
          self.cache[args] = value
          return value      
       except TypeError:
          # uncachable. better to not cache than to blow up entirely
          return self.func(*args)
      
    def __repr__(self):
       """return the function's docstring"""
       return self.func.__doc__
   
    def __get__(self, obj, objtype):
       """support instance methods"""
       return functools.partial(self.__call__, obj)