Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2: someIterator.next() vs. next(someIterator) :Python 3

In Python 2 iterators offer .next(), a callable method:

it = iter(xrange(10))
it.next()
> 0
it.next()
> 1
...

In Python 3 one has to use the built-in function next():

it = iter(range(10))
next(it)
> 0
next(it)
> 1
...

Is this just "syntactic sugar"? Like making it more obvious to use next() by moving it into the built-in functions? Or does any advanced concept hide behind this change?

like image 900
daniel451 Avatar asked Feb 11 '26 10:02

daniel451


1 Answers

You are directly asking about PEP 3114

consider the following code:

class test:
    def __iter__(self):
        return self
    def next(self):
        return "next"
    def __next__(self):
        return "__next__"

x = test()
for i,thing in enumerate(x):
    print(thing)
    if i>4:
        break

in python 2 next is printed but in python 3 __next__ is printed, since the method is being called implicitly it makes way more sense to match other implicit methods such as __add__ or __getitem__, which is described in the PEP.

If you are planning on using next explicitly then much like len, iter, getattr, hash etc. then python provides a built in function to call the implicit function for you. At least... after PEP 3114. 😀

Also, the next built-in allows you pass a default value if you don't want to throw an error if the iterable is finished which is frequently useful:

it = iter([])
x = next(it, "pls don't crash")

which couldn't really be standardized for a .next() method call. As well objects such as a random number generator may define a .next (next number) method without necessarily wanting to be an iterator which could have left ambiguity / confusion.

like image 199
Tadhg McDonald-Jensen Avatar answered Feb 14 '26 12:02

Tadhg McDonald-Jensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!