python resettable instance method memoization decorator

前端 未结 3 1991
旧巷少年郎
旧巷少年郎 2020-12-16 02:41

I\'m attempting to build a decorator for an instance method of a class that will memoize the result. (This has been done a million times before) However, I\'d like the optio

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 02:59

    Well, I would like to point out two performance issues in your code. This is not an answer to your question, but I can't make it a comment. Thanks to @delnan for pointing out that has_key is deprecated. Instead of:

        try:
            return self.cache[key]
        except KeyError:
            self.cache[key] = self.func(*args, **kwargs)
            return self.cache[key]
        except TypeError:
            # uncacheable, so just return calculated value without caching
            return self.func(*args, **kwargs)
    

    I would make it this way:

    resultDone = False
    result = None
    try:
      if key in self.cache: return self.cache[key]
      else:
        result = self.func(*args, **kwargs)
        resultDone = True
        self.cache[key] = result
    except TypeError: # unhashable key
      pass
    if resultDone: return result
    else: return self.func(*args, **kwargs)
    

    This avoids: a) try/except KeyError; b) calling cache[key] on return; c) calling the function once more on unhashable keys.

提交回复
热议问题