from sortedcontainers import SortedSet
class BigSet(object):
def __init__(self):
self.set = SortedSet()
self.current_idx = -1
def __getitem__(self, index):
try:
return self.set[index]
except IndexError as e:
print('Exception: Index={0} len={1}'.format(index, len(self.ord_set)))
raise StopIteration
def add(self, element):
self.set.add(element)
def __len__(self):
return len(self.set)
def __iter__(self):
self.current_idx = -1
return self
def __next__(self):
self.current_idx += 1
if self.current_idx == len(self.set):
raise StopIteration
else:
return self.set[self.current_idx]
def main():
big = BigSet()
big.add(1)
big.add(2)
big.add(3)
for b in big:
print(b)
for b2 in big:
print(b2)
if __name__ == "__main__":
main()
I have a class that embeds an iterable member variable named self.set
and I would like to enable this class to support for
loop. The above is the code that I wrote for the purpose. However, I think there must be a better way to do this task easier since the class has an iterable member already.
Question> Is there a way that I can delegate the job to the embedded self.set
? Also, I think there maybe a good way to implement the __getitem__
too.
Thank you