Created
February 1, 2019 17:41
-
-
Save saintsGrad15/474639b9e7b0f929f4cafb430e2a8ecb to your computer and use it in GitHub Desktop.
A simple list implementation that yields None or a defined default if an out-of-bounds index is referenced.
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, iterable=[], default=None): | |
super(self.__class__, self).__init__(iterable) | |
self.default = default | |
def __getitem__(self, index): | |
""" | |
If 'index' is outside of the bounds (including negative indexing) of the list, | |
return 'self.default.' | |
:param: index (int): The numerical index to return. | |
:return: (any) The element at index 'index.' | |
If that index doesn't exist, 'self.default.' | |
""" | |
length = len(self) | |
if index in range(-1 * length, length): | |
return super(self.__class__, self).__getitem__(index) | |
else: | |
return self.default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment