I have a generator that generates a series, for example:
def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
In Python 2 I am able to make the following calls:
g = triangle_nums() # get the generator g.next() # get the next value
however in Python 3 if I execute the same two lines of code I get the following error:
AttributeError: 'generator' object has no attribute 'next'
but, the loop iterator syntax does work in Python 3
for n in triangle_nums():
if not exit_cond:
do_something()...
I haven’t been able to find anything yet that explains this difference in behavior for Python 3.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or “dunder” in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]
But instead of calling g.__next__(), use next(g).
[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.
Method 2
Try:
next(g)
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
Method 3
If your code must run under Python2 and Python3, use the 2to3 six library like this:
import six six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0