Created
March 14, 2017 13:36
-
-
Save maxnordlund/7a8ed9626f2109d4bf688604a6ac324b to your computer and use it in GitHub Desktop.
Default list in python, á la defaultdict.
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
class DefaultList(list): | |
""" | |
List that always returns a value | |
If you try to access an missing index, it will fill up this list with | |
empty lists for all missing indices before returning the requested | |
index. This will be the last element since lists are ordered. | |
A consequence of this is that `for` loops over this list will never | |
stop. | |
""" | |
def __getitem__(self, index): | |
try: | |
# This also handles slice objects, which always will return a | |
# new list, and can thus never fail | |
return super().__getitem__(index) | |
except IndexError: | |
# Fill the list with empty ones upto the requested index | |
self[len(self):index + 1] = ([] for _ in range(len(self), index + 1)) | |
return super().__getitem__(index) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment