I want to create, in Python, a class behaving like a list but that could be iterated circularly use case example:
myc = SimpleCircle()
print(len(myc))
j = iter(myc)
for i in range (0, 5):
print(next(j))
it will print a b c d a
the code I tried so far is the one below
I know the issue is with my __next__
method which by the way seems ignored, I can use next even if I don't implement it
class SimpleCircle:
def __init__(self):
self._circle = ['a', 'b', 'c', 'd']
self._l = iter(self._circle)
def __len__(self):
return len(self._circle)
def __iter__(self):
return (elem for elem in self._circle)
def __next__(self):
try:
elem = next(self._l)
idx = self._circle.index(elem)
if idx < len(self._circle):
return elem
else:
return self._circle[0]
except StopIteration:
pass