[Python-Dev] iterator API in Py3.0

Raymond Hettinger raymond.hettinger at verizon.net
Fri Mar 3 21:14:06 CET 2006

> * As a writer/teacher, I want to be able to say, "All Python special
> methods have leading and trailing double-underscore."  Period, end of
> story.

When teaching your classes, do you sense an aversion to using double underscore 
methods in regular code?  I sense an implied message that these methods are not 
intended to be called directly (i.e. the discomfort of typing x.__setitem__(k,v) 
serves as a cue to write x[k]=v instead; likewise, x.__int__() pushes towards 
int(x) instead).

If so, then that is a good reason to leave it.next() as-is.  Unlike __setitem__ 
or __int__, the next() method is intended to be called directly in normal code. 
Of course, for-loops are the most common case and it makes no difference there; 
however, in the rest of the cases where the iterator is accessed directly, the 
current naming is clean, readable, and doesn't provide an aversive cue.

The double underscore convention is appropriate where the method is always 
invoked magically in normal code and not called directly.  The next() method is 
differenct because it is a mixed case, sometimes called magically and sometimes 
called directly.  In the latter case, the name is highly visible and therefore 
should not have double underscores.

I suspect that those who feel differently are ones who usually avoid calling 
next() directly.  That's okay, but we shouldn't muck-up the naming for the rest 
of us who often do have a need to use next().

This is doubly important because we're now expanding the protocol to include 
send() and throw().  Adding underscores around them too will only make those 
methods look harder to use than they actually are.  Don't underestimate the 
psychological revulsion to calling code filled with piles of double underscores.

> As for your point about efficiency, I don't much care whether we get a
> built-in next() function, but I think that anyone who is concerned about
> efficiency should do
>    next = obj.__next__

There are plenty of places to blow-off efficiency.  This iterator protocol is 
not one of them.  Looping constructs need to be as lightweight as possible.

Code like "next=obj.__next__" should be avoided as much as possible.  It is 
ugly, it incidental to the expression of an algorithm, and it should not be 


More information about the Python-Dev mailing list