What is the most pythonic way to conditionally compute?
I would use a sibling of defaultdict
for this (you can't use defaultdict
directly since it won't tell you the key that is missing):
class Cache(object): def __init__(self): self.cache = {} def get(self, a, b): key = (a,b) result = self.cache.get(key, None) if result is None: result = likelihood(data, a, b) self.cache[key] = result return result
Another approach would be using a cache decorator on likelihood
as described here.