Property that maps to a key in a local dict-like attribute.
| 157 | |
| 158 | |
| 159 | class DictProperty(object): |
| 160 | ''' Property that maps to a key in a local dict-like attribute. ''' |
| 161 | def __init__(self, attr, key=None, read_only=False): |
| 162 | self.attr, self.key, self.read_only = attr, key, read_only |
| 163 | |
| 164 | def __call__(self, func): |
| 165 | functools.update_wrapper(self, func, updated=[]) |
| 166 | self.getter, self.key = func, self.key or func.__name__ |
| 167 | return self |
| 168 | |
| 169 | def __get__(self, obj, cls): |
| 170 | if obj is None: return self |
| 171 | key, storage = self.key, getattr(obj, self.attr) |
| 172 | if key not in storage: storage[key] = self.getter(obj) |
| 173 | return storage[key] |
| 174 | |
| 175 | def __set__(self, obj, value): |
| 176 | if self.read_only: raise AttributeError("Read-Only property.") |
| 177 | getattr(obj, self.attr)[self.key] = value |
| 178 | |
| 179 | def __delete__(self, obj): |
| 180 | if self.read_only: raise AttributeError("Read-Only property.") |
| 181 | del getattr(obj, self.attr)[self.key] |
| 182 | |
| 183 | |
| 184 | class cached_property(object): |