4 ms·
You could just use a small memoize decorator like this one class Memoize: def __init__ (self, f): self.f = f self.mem = {} def __call__ (self, *args, *
by pizza 16y ago
You could just use a small memoize decorator like this one
class Memoize:
def __init__ (self, f):
self.f = f
self.mem = {}
def __call__ (self, *args, **kwargs):
if (args, str(kwargs)) in self.mem:
return self.mem[args, str(kwargs)]
else:
tmp = self.f(*args, **kwargs)
self.mem[args, str(kwargs)] = tmp
return tmp
- gaius 16y agoYes you can cheat if you use your own memoizer too, if you "know" what your function does. Mine f'rinstance memoizes data fetched over the network even tho' as a function that is wildly impure, it can either age it out or check the last modification time. So I have one decorator for pure computations performed locally and impure performed remotely. Obviously this can only be done if the same person/team is maintaining both or it'll all go horribly wrong...
- ntoshev 16y agoYou should str(args), not just kwargs, to be able to use parameters like lists or dicts as keys for self.mem
- asmosoinio 16y agoNot the same at all: IncPy stores the results to disc, so you can rerun your script and it will still have correct cache results for long running functions.
- pgbovine 16y agogreat point; the persistence of the IncPy cache is one of the biggest differentiators from an ordinary memoize decorator