Skip to content

Instantly share code, notes, and snippets.

@japborst
Created September 5, 2016 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save japborst/9ab8132f0b284676819298d14d58b772 to your computer and use it in GitHub Desktop.
Save japborst/9ab8132f0b284676819298d14d58b772 to your computer and use it in GitHub Desktop.
A list alternative to the very useful collections.defaultdict
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