Iterator Types

The iterator type in RPython is similar with Python, it can help to iterator over containers. The iterator objects should support __iter__() and next() methods. These two methods form the iterator protocol.

class Counter():
    c = 100

    def __iter__(self):
        return self

    def next(self):
        t = self.c
        self.c += 1
        return t

def iterator():
    l = [1, 2, 3, 4, 5]

    it = iter(l)    # return an iterator object on the list l
    print it.next() # get next item from the list

    c = Counter()

    it = c.__iter__()
    print it.next()
    print next(it)

def iterator_unsupported():
    l = [1, 2, 3, 4, 5]

    # __iter__() method for list is not supported in RPython
    it = l.__iter__()
    print it.next()

def entry_point(argv):
    iterator()
    return 0

def target(*args): return entry_point

if __name__ == "__main__":
    import sys
    entry_point(sys.argv)
    iterator_unsupported()

Attention

You cannot get an iterator object of a list using the __iter__() method in RPython.

If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object with the __iter__() and next() method. Here is an example of a customized container object implemented the iterator protocol using generator.

class Box():
    content = []

    def add(self, cat):
        self.content.append(cat)

    def __iter__(self):
        for i in self.content:
            yield i

def iterator_generator():
    b = Box()
    b.add("Tiger")
    b.add("Kitty")

    it = b.__iter__()
    print it.next()

    for i in b:
        print i

def entry_point(argv):
    iterator_generator()
    return 0

def target(*args): return entry_point
if __name__ == "__main__": import sys; entry_point(sys.argv)