Tharanga Abeyseela Tharanga Abeyseela - 3 months ago 10
Python Question

Type error Iter - Python3

Can someone please explain why the following code is giving

TypeError: iter() returned non-iterator of type 'counter' in python 3


This is working in python 2.7.3 without any error.

#!/usr/bin/python3

class counter(object):

def __init__(self,size):
self.size=size
self.start=0

def __iter__(self):
print("called __iter__",self.size)
return self

def next(self):
if self.start < self.size:
self.start=self.start+1
return self.start
raise StopIteration

c=counter(10)
for x in c:
print(x)

Answer

In python3.x you need to use __next__() instead of next() .

from What’s New In Python 3.0:

PEP 3114: the standard next() method has been renamed to __next__().

If you want your object to be iterable in both python 2.X and 3.X you can assign your next function to name __next__ too:

class counter(object):

    def __init__(self,size):
        self.size=size
        self.start=0

    def __iter__(self):
        print("called __iter__",self.size)
        return self

    def next(self):
        if self.start < self.size:
            self.start=self.start+1
            return self.start
        raise StopIteration

    __next__ = next # Python 3.X compatibility