Home > Back-end >  Lazy evaluation of dict values?
Lazy evaluation of dict values?

Time:11-13

Suppose I have the following dict d={'a': heavy_expression1, 'b': heavy_expression2}.

How can I wrap the expressions, so that they are evaluated once they are accessed and after this no evaluation is performed?

d['a'] # only here heavy_expression1 is executed
d['a'] # no execution here, already calculated

Do I need to use lambda or generators?

CodePudding user response:

A version with lambdas:

class LazyDict(dict):
    def __init__(self, lazies):
        self.lazies = lazies
    def __missing__(self, key):
        value = self[key] = self.lazies[key]()
        return value

d = LazyDict({'a': lambda: print('heavy_expression1') or 1,
              'b': lambda: print('heavy_expression2') or 2})
print(d['a'])
print(d['a'])
print(d['b'])
print(d['b'])

Output:

heavy_expression1
1
1
heavy_expression2
2
2
  • Related