Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why isn't "next()" called "__next__()"

I'm using Python 2.7.

By convention, builtin methods like __iter__, __init__, __str__, etc. have the double underscore to identify them as such. Why doesn't the next() function have this?

It features alongside the other built-in functions here: https://docs.python.org/2/library/functions.html and this doesn't seem like a very consistent convention.

like image 668
kd88 Avatar asked Sep 24 '26 21:09

kd88


2 Answers

The built-in function doesn't have __ because none of the built-ins do. You're confusing built-ins (like str) with special methods (like __str__).

Now the special method called by the built-in next is also called next in Python 2.7, but that naming was recognized as an accident and changed to __next__ in Python 3.

like image 66
Fred Foo Avatar answered Sep 27 '26 12:09

Fred Foo


It was in Python v3.x. And is still there for backwards compatibility. From http://docs.pythonsprints.com/python3_porting/py-porting.html:

Python 3 introduced a next() function to replace the next() method on iterator objects. Rather than calling the method on the iterator, the next() function is called with the iterable object as its sole parameter, which calls the underlying __next__() method.

like image 24
Luke Peterson Avatar answered Sep 27 '26 11:09

Luke Peterson



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!