Created
December 12, 2014 10:20
-
-
Save vinodc/c53bb1b37e46160717cb to your computer and use it in GitHub Desktop.
Lazy dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Wrote this before realizing django.utils.functional.lazy existed. | |
class LazyDict(dict): | |
""" | |
Loads data lazily. | |
""" | |
def __init__(self, loader, *args, **kwargs): | |
self._data_loaded = False | |
self.loader = loader | |
super(LazyDict, self).__init__(*args, **kwargs) | |
def load_data(func): | |
def _dec(*args, **kwargs): | |
self = args[0] | |
if not self._data_loaded: | |
self._load_data() | |
return func(*args, **kwargs) | |
return _dec | |
@load_data | |
def __getitem__(self, k): | |
return super(LazyDict, self).__getitem__(k) | |
@load_data | |
def __setitem__(self, k, v): | |
return super(LazyDict, self).__setitem__(k, v) | |
@load_data | |
def __contains__(self, k): | |
return super(LazyDict, self).__contains__(k) | |
@load_data | |
def __delitem__(self, k): | |
return super(LazyDict, self).__delitem__(k) | |
def _load_data(self): | |
data = self.loader() | |
for k, v in data.items(): | |
super(LazyDict, self).__setitem__(k, v) | |
self._data_loaded = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment