Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 909
AlexLordThorsen Avatar asked Apr 11 '15 13:04

AlexLordThorsen


People also ask

What does __ ITER __ do in Python?

The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.

How do you make an object iterable in Python?

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.

What are different ways you can obtain an iterator from Python?

Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol. An object is called iterable if we can get an iterator from it.

Can we create an iterator object from a list?

Iterable is an object, which one can iterate over. It generates an Iterator when passed to the iter() method. Lists, tuples, dictionaries, strings and sets are all iterable objects. They are iterable containers that you can convert into an iterator.


1 Answers

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
like image 157
Martijn Pieters Avatar answered Nov 13 '22 06:11

Martijn Pieters