generator/coroutine terminology

Chris Angelico rosuav at gmail.com
Tue Mar 31 11:36:50 EDT 2015


On Wed, Apr 1, 2015 at 2:03 AM, Albert van der Horst
<albert at spenarnc.xs4all.nl> wrote:
> class Squares:
>     def __init__(self):
>         self.i = 0
>     def __next__(self):
>         self.i += 1
>         return self.i**2
>     def __iter__(self):
>         return self
>
> albert at cherry:/tmp$ python
> Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from aap import *
>>>> for i in Squares():
> ...     print i
> ...     if i>50: break
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: instance has no next() method
>>>>
>
> / --------------------------
>
> Probably not what is intended.
>
> Last minute note:
>    renaming __next__() into next() did the job.

That class was written for Python 3, not Python 2. In Py2, you need to
rename __next__ to next, as you noted, and you probably also want to
explicitly subclass object. Or just run it under Python 3. :)

ChrisA



More information about the Python-list mailing list