Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 352
Tharanga Abeyseela Avatar asked Jan 30 '15 23:01

Tharanga Abeyseela


1 Answers

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__().

However, if you want your object to be iterable both in python 2.X and 3.X you can assign your next function to the name __next__.

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
like image 172
Mazdak Avatar answered Oct 05 '22 03:10

Mazdak