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
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.