Last active
August 29, 2015 14:03
-
-
Save vartagg/48f7fed70a480409631d to your computer and use it in GitHub Desktop.
This file contains 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
from copy import copy | |
class LazyDict(dict): | |
""" | |
A dict class with default value for unfound keys | |
>>> ldict = LazyDict(0) | |
>>> ldict | |
{} | |
>>> ldict['x'] += 1 | |
>>> ldict | |
{'x': 1} | |
>>> ldict['x'] += 1 | |
>>> ldict | |
{'x': 2} | |
>>> ldict['y'] += 10 | |
>>> ldict == {'x': 2, 'y': 10} | |
True | |
>>> ldict['z'] == 0 | |
True | |
>>> ldict == {'x': 2, 'y': 10, 'z': 0} | |
True | |
>>> ldict = LazyDict([]) | |
>>> ldict | |
{} | |
>>> ldict['a'].append(20) | |
>>> ldict['a'].append(20) | |
>>> ldict | |
{'a': [20, 20]} | |
>>> ldict['b'].append(6) | |
>>> ldict == {'a': [20, 20], 'b': [6]} | |
True | |
""" | |
def __init__(self, default_value): | |
super(LazyDict, self).__init__() | |
self._default_value = default_value | |
def __getitem__(self, item): | |
if not item in self: | |
self.__setitem__(item, copy(self._default_value)) | |
return super(LazyDict, self).__getitem__(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment