How to make an object both an iterator of Python2 and Python3?

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

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

How to make an object that is an iterator in both Python 2 and 3?

+8
python iterator
source share
1 answer

Just give it the __next__ and next method; one may be the alias of the other:

 class Iterator(object): def __iter__(self): return self def __next__(self): # Python 3 return 'a value' next = __next__ # Python 2 
+20
source share

All Articles