Created
September 5, 2016 09:44
-
-
Save japborst/9ab8132f0b284676819298d14d58b772 to your computer and use it in GitHub Desktop.
A list alternative to the very useful collections.defaultdict
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
class DefaultList(list): | |
def __init__(self, factory=None): | |
super(DefaultList, self).__init__() | |
# Check if argument is callable | |
if factory is not None: | |
try: | |
factory() | |
except TypeError as e: | |
raise e | |
self._factory = factory | |
def __repr__(self): | |
return "%s(%s, %s)" % (self.__class__.__name__, self._factory, super(DefaultList, self).__repr__()) | |
def _fill(self, index): | |
while len(self) <= index: | |
if self._factory is None: | |
self.append(self._factory) | |
else: | |
self.append(self._factory()) | |
def __setitem__(self, index, value): | |
self._fill(index) | |
super(DefaultList, self).__setitem__(index, value) | |
def __getitem__(self, index): | |
self._fill(index) | |
return super(DefaultList, self).__getitem__(index) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment