Skip to content

Instantly share code, notes, and snippets.

@matteodellamico
Created December 6, 2020 18:35
Show Gist options
  • Save matteodellamico/99fea373b5ffb7351ff4ec9d29f7c978 to your computer and use it in GitHub Desktop.
Save matteodellamico/99fea373b5ffb7351ff4ec9d29f7c978 to your computer and use it in GitHub Desktop.
A quick&dirty approach to enable efficient `a + b + c + d + e` behavior in a list-like object
from collections.abc import MutableSequence
from itertools import chain
class LazyList(list):
def __add__(self, other):
return LazyListSum((self, other))
class LazyListSum(MutableSequence):
def __init__(self, params):
self.__params = params
self.__the_list = None
def __add__(self, other):
return LazyListSum(self.__params + (other,))
def getlist(self):
the_list = self.__the_list
if the_list is None:
# print("Concatenation!")
self.__the_list = the_list = list(chain(*self.__params))
return the_list
def __getitem__(self, item):
return self.getlist()[item]
def __setitem__(self, item, value):
self.getlist()[item] = value
def __delitem__(self, item):
del self.getlist()[item]
def __len__(self):
return len(self.getlist())
def __hasattr__(self, attr):
return hasattr(self.getlist(), attr)
def insert(self, index, object):
return self.getlist().insert(index, object)
if __name__ == '__main__':
l0 = LazyList([42, 23])
l1 = l0 + [1,2] + [5, 6]
for item in l1: # concatenation is computed only here, when we start doing something
print(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment