Pseudo-sequence object: Exception needed to terminate?

Viewed 34

I lived with the assumption, that defining the _ _len_ _ and _ _getitem_ _ methods are sufficient for a class, so its instances can be iterated over via a for element in instance:, until it got violated an example. My original code is quite different, but this shows the problem nicely entering an endless loop:

class Limited(object):
    def __init__(self, size=5):
        self.size = size

    def __len__(self):
        return self.size

    def __getitem__(self, item):
        return item*10

if __name__ == "__main__":
    test = Limited(4)
    assert len(test) == 4

    for q in test:
        print q

I could not find a specific reference to the requirements for terminating an iteration loop, but it seems that an exception like an IndexError or StopIteration is necessary for termination, if one does not want to comply to full Iterator protocol.

Is that correct and where to find it documented?

2 Answers
Related