Python Iterables

Posted on Monday May 2nd, 2016

Recently I inverstigated how to make a python object iterable. It seems that it uses two overloadable methods called __iter__ and next which are actually called by iter() and next() respectively.

It seems that iter() initiates the iteration process while next() expects the next item with each iteration until StopIteration is thrown.

class MyIter():
    """A class that can iterate"""

    def __init__(self, start, stop):
        """Create the environment for the iterator

        start: the returned value of the first iteration
        stop: the returned value of the last iteration
        """
        self.start = start
        self.stop = stop

    def __iter__(self):
        """Setup the class for iteration which then uses next for sequencing"""
        self.itval = self.start - 1
        return self

    def next(self):
        """return the next item in the iteration or raise StopIteration"""
        if self.itval == self.stop:
            raise StopIteration
        self.itval += 1
        return self.itval

Example run:

>>> foo = MyIter(3,7)
>>> for i in foo:
...     print i
...
3
4
5
6
7