8

This Stack Overflow post is about making an object an iterator in Python.

In Python 2, that means you need to implement an __iter__() method, and a next() method. But in Python 3, you need to implement a different method, instead of next() you need to implement __next__().

How does one make an object which is an iterator in both Python 2 and 3?

Community
  • 1
  • 1
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103

1 Answers1

25

Just give it both __next__ and next method; one can be an alias of the other:

class Iterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        # Python 3
        return 'a value'

    next = __next__  # Python 2
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343