Proposed new syntax

Steve D'Aprano steve+python at pearwood.info
Thu Aug 24 09:45:13 EDT 2017


On Thu, 24 Aug 2017 06:21 pm, Paul Rubin wrote:

> Peter Otten <__peter__ at web.de> writes:
>> Python 3 where the next() method has been renamed to __next__().
> 
> Oh cripes, you're right, it never occurred to me that py3 had broken
> .next().  I thought it was called .next() instead of .__next()
> so that it wouldn't be a dunder method.

Not so much *broken* it as *fixed* it :-)

Guido decided years ago that directly exposing next as a public method was a
mistake. Instead, like len(), str(), repr(), iter() etc. the public API is to
call the next() built-in function, and the implementation is the __next__
dunder.

I don't remember whether that decision was just for consistency with other
special methods, or whether there was some other deeper reason... 

Possibly so it was easy to add a default value to next() without having to force
every iterator class to re-implement the same default behaviour? That seems
reasonable... in Python 2.7, the next method takes no default argument:

py> iter("").next(99)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: expected 0 arguments, got 1

but the built-in function does:

py> next(iter(""), 99)
99


In general, the public API function (whether built-in like next, or not) can do
much more than just call the dunder method, e.g. look at the various operators.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list