Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the interface for python iterators? [duplicate]

Possible Duplicate:
Build a Basic Python Iterator

What are the required methods for defining an iterator? For instance, on the following Infinity iterator, are its methods sufficient? Are there other standard or de facto standard methods that define an iterator?

class Infinity(object):
    def __init__(self):
        self.current = 0

    def __iter__(self):
        return self

    def next(self):
        self.current += 1
        return self.current
like image 584
Arion Avatar asked Oct 26 '12 21:10

Arion


People also ask

What is iterator interface in Python?

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol.

What should __ ITER __ return?

__iter__ returns the iterator object itself and the __next__ method returns the next value from the iterator. If there is no more items to return then it raises a StopIteration exception.

Which method is used to define iterators in Python?

Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.

IS FOR loop an iterator in Python?

StopIteration: Under the hood, Python's for loop is using iterators.


2 Answers

What you have is sufficient for Python 2.x, but in Python 3.x you need to define the function __next__ instead of next, see PEP 3114.

If you need code that is compatible with both 2.x and 3.x, include both.

like image 61
Andrew Clark Avatar answered Oct 13 '22 20:10

Andrew Clark


According to the glossary, an iterator is any object with a next() method, and a __iter__() method.

like image 42
unutbu Avatar answered Oct 13 '22 22:10

unutbu