Many thanks to everyone who contributed ideas! Here is what I gathered from all the answers. This retains a lot of functionality from the regular list class, adding extra behavior when necessary to meet additional requirements.
class DynamicList(list): def __init__(self, gen): self.gen = gen def __getitem__(self, index): while index >= len(self): self.append(next(self.gen)) return super(DynamicList, self).__getitem__(index) def __getslice__(self, start, stop):
Previously created values can be obtained individually as elements or slices. The recorded history is expanded as necessary if the requested item is outside the current end of the list. You can access the entire recorded history at a time using print a
or assigned to a regular list using b = a[:]
. A slice of recorded history can be deleted with del a[0:4]
. You can iterate over the entire list using for
, deleting along the way or when it suits. If you reach the end of the generated values, StopIteration
will be raised.
Some awkwardness remains. Assignments such as a = a[0:4]
successfully truncate the history, but the resulting list is no longer auto-expanded. Instead, use del a[0:4]
to maintain automatic growth properties. In addition, I am not entirely satisfied with the recognition of the magic value 2147483647
, representing the very last element.
source share