]> git.phdru.name Git - m_lib.git/blob - m_lib/lazy/dict.py
c6750e4372c5ce7f08ba2bad69c4db80ea3c2440
[m_lib.git] / m_lib / lazy / dict.py
1 "Lazy dictionaries calculate self content upon first access"
2
3 class LazyDict:
4    "Abstract parent of all lazy dictionaries"
5
6    def _init(self):
7       raise NotImplementedError
8
9    def __getattr__(self, attr):
10       if self.data is None: self._init()
11       return getattr(self.data, attr)
12
13    def __getitem__(self, key):
14       if self.data is None: self._init()
15       return self.data[key]
16
17    def __setitem__(self, key, value):
18       if self.data is None: self._init()
19       self.data[key] = value
20
21
22 class LazyDictInitFunc(LazyDict):
23    "Lazy dict that initializes itself by calling supplied init function"
24
25    def __init__(self, init=None, *args, **kw):
26       self.init = init
27       self.data = None
28       self.args = args
29       self.kw = kw
30
31    def _init(self):
32       init = self.init
33       if init is None:
34          data = {} # just a new empty dict
35       else:
36          data = init(*self.args, **self.kw)
37       self.data = data