Last active
February 28, 2021 17:00
-
-
Save ansaso/325959e903c0a603c92060006ac49992 to your computer and use it in GitHub Desktop.
pyhton's collections.DefaultDict but for lists. Quick mockup
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): | |
def __init__(self, list_, default=None): | |
super().__init__(list_) | |
self.default = default | |
def __getitem__(self, index): | |
if isinstance(index, slice): | |
start = index.start | |
stop = index.stop | |
step = index.step | |
length = super().__len__() | |
# [1,2,3][:] | |
if stop is None: | |
return super().__getitem__(index) | |
# [1,2,3][:100] | |
if length < stop: | |
extra = [self.default] * (stop - length - 1) | |
original = super().__getitem__(slice(start, length)) | |
return (original + extra)[slice(None, None, step)] | |
try: | |
# [1,2,3][0] | |
return super().__getitem__(index) | |
except IndexError: | |
# [1,2,3][100] | |
return self.default | |
def test_DefaultList(): | |
li = [0,1,2,3,4,5,6,7,8] | |
dli = DefaultList([0,1,2,3,4,5,6,7,8]) | |
# listlike | |
assert dli[:] == li[:] | |
assert dli[:3] == li[:3] | |
assert dli[-3:] == li[-3:] | |
assert dli[::2] == li[::2] | |
assert dli[3:-3] == li[3:-3] | |
# non-listlike | |
assert dli[10] == None | |
assert dli[10:12] == [None, None] | |
assert dli[7:11] == [7,8,None] | |
assert dli[-2:11] == [7,8,None] | |
# methods | |
dli.append(9) | |
li.append(9) | |
dli == li | |
dli.pop() == li.pop() | |
test_DefaultList() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment