########## # # Decorations # class Memoized(dict): """ A function wrapper to cache the results of functions that take a long time to complete, like database querries or intensive mathematical computations.
To wipe the cache, just call m.clear() """ def __init__(self, func, init={}): """ Accepts the function to be memoized and an optional initial dictionary of known results. """ dict.__init__(self, init) self.func = func
def __call__(self, *args, **kwds): key = (args, tuple(kwds.items())) # hope everything's hashable... return ( self.get(key) or self.setdefault(key, self.func(*args, **kwds)) )
I believe that with standard dictionaries, kwds is not guaraneed to have any particular order. Perhaps sorting kwds.items() makes sense? - Josiah
On Sun, 2004-04-04 at 01:37, Josiah Carlson wrote:
def __call__(self, *args, **kwds): key = (args, tuple(kwds.items())) # hope everything's hashable... return ( self.get(key) or self.setdefault(key, self.func(*args, **kwds)) )
I believe that with standard dictionaries, kwds is not guaraneed to have any particular order. Perhaps sorting kwds.items() makes sense?
Also the call to self.func() is needlessly repeated if the return value is 0, None, or anything else that is treated as False. I realise that this is off the point slightly, but using "e1 or e2" like this is such an attractive nuisance it warrants being stomped on wherever possible. Mark Russell
participants (3)
-
foo
-
Josiah Carlson
-
Mark Russell