[Tutor] Generator next()

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Dec 27 20:16:22 CET 2013


On Dec 27, 2013 6:24 PM, "Keith Winston" <keithwins at gmail.com> wrote:
>
> I am beginning to think about decorators, generators, and the like. I'm
starting from zero. I've read a few PEPs, and looked at some code, and
maybe things are starting to sink in, though I don't really have enough
framework to hang it all on. It'll come. Anyway, I was trying to run some
timing code I swiped off the web, but ran into a problem with the .next()
function, which I THINK relates to the changes between how generators are
implemented between pre-3.3 and post, but I can't really tell. Here's the
code, stolen without apology from here:
http://enja.org/2011/03/09/a-python-function-timing-decorator/
>
(snip)
>
> And here's the error message:
>
> Traceback (most recent call last):
>   File "/home/keithwins/Dropbox/Python/timer1.py", line 50, in <module>
>     timings = Timing()
>   File "/home/keithwins/Dropbox/Python/timer1.py", line 7, in __init__
>     self.col.next() #coroutine syntax
> AttributeError: 'generator' object has no attribute 'next'

The next method of iterators was renamed __next__ in Python 3. So if you
change it to self.col.__next__() it will work in Python 3. Neither of those
is really correct though. The correct method is to call the next built-in:
    next(self.col)
That will work under Python 2 and 3 and is the recommended way in both
versions.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131227/8b8e3771/attachment.html>


More information about the Tutor mailing list