1

I want to memoize the result of a function in a class:

class memoize:
    def __init__(self, function):
        self.function = function
        self.memoized = {}

    def __call__(self, *args):
        try:
            return self.memoized[args]
        except KeyError, e:
            self.memoized[args] = self.function(*args)
            return self.memoized[args]

class DataExportHandler(Object):
    ...

    @memoize
    def get_province_id(self, location):
        return search_util.search_loc(location)[:2] + '00000000'

    def write_sch_score(self):
        ...
        province_id = self.get_province_id(location)

but this doesn't work, because it tells me that get_province_id takes exactly 2 arguments(1 given)

Jeff
  • 12,147
  • 10
  • 51
  • 87
roger
  • 9,063
  • 20
  • 72
  • 119

2 Answers2

0

There are a few examples of Memoizing decorators here that are worth taking a look at. The second and third examples I think probably address the issues with methods vs functions better.

-1

The member function can not use a class decorator, you should use a function decorator:

def memoize1(obj):
    cache = obj.cache = {}

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            print 'not in cache'
            cache[key] = obj(*args, **kwargs)
        else:
            print 'in cache'
        return cache[key]
    return memoizer
guozengxin
  • 19
  • 1