5

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
Arion
  • 1,792
  • 2
  • 18
  • 29

3 Answers3

7

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 3
    @Arion: To define both, just add the statement `__next__ = next` at the end of the body of your class. – martineau Oct 26 '12 at 21:25
1

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

Section 4.5 - Iterator Types

You need to define for your container:

container.__iter__() #-> returns iterator

and for your iterator your must define:

iterator.__iter__() #-> returns self
iterator.__next__() #-> returns next item
iterator.next() #(for Python2 compatibility) -> returns self.__next__()
matt2000
  • 1,064
  • 11
  • 17
Alex
  • 6,843
  • 10
  • 52
  • 71