Real world usage of __iter__ and next

By : Akshar Raaj

This post assumes that you have a basic understanding of the iterator protocol. If not read our last post.

Real world usage of __iter__

Implementing xrange

There is a builtin function called xrange. It is very similar to list. xrange yields the same values as the corresponding list, without actually storing them all simultaneously. Since it doesn't store all values simultaneously, so it saves memory.

If xrange were not there, it could have been implemented in following way using iterators:

In [12]: class xrange_iterator(object):
    ...:     def __init__(self, max):
    ...:         self.max = max
    ...:         self.current = 0
    ...:     def next(self):
    ...:        if ...

more info..
Topics : python

Iterators and Iterables

By : Akshar Raaj


Iterables are objects that implement the iterator protocol.

Iterator protocol mandates that __iter__ method be implemented on the object.

class A(object):
    def __iter__(self):
        return B()

An instance of A would be an iterable, because class A has __iter__() defined on it.

__iter__ method mandates that an iterator be returned from it. Instance of class B must be an iterator. More on iterators to follow. iterator and iterables are different things.

a = A()

Here "a" is an iterable. It is not an iterator.

There is a built-in method called iter(). Only iterables can be passed to built in ...

more info..
Topics : python
© Agiliq, 2009-2012