Skip to content

Commit a18af4e

Browse files
committed
PEP 3114: rename .next() to .__next__() and add next() builtin.
1 parent 4d2adcc commit a18af4e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

83 files changed

+496
-426
lines changed

Doc/api/newtypes.tex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1071,7 +1071,7 @@ \section{Type Objects \label{type-structs}}
10711071
iterator, or raises \exception{StopIteration} when the iterator is
10721072
exhausted. Its presence normally signals that the instances of this
10731073
type are iterators (although classic instances always have this
1074-
function, even if they don't define a \method{next()} method).
1074+
function, even if they don't define a \method{__next__()} method).
10751075

10761076
Iterator types should also define the \member{tp_iter} function, and
10771077
that function should return the iterator instance itself (not a new

Doc/howto/functional.rst

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,13 @@ foundation for writing functional-style programs: iterators.
199199

200200
An iterator is an object representing a stream of data; this object
201201
returns the data one element at a time. A Python iterator must
202-
support a method called ``next()`` that takes no arguments and always
202+
support a method called ``__next__()`` that takes no arguments and always
203203
returns the next element of the stream. If there are no more elements
204-
in the stream, ``next()`` must raise the ``StopIteration`` exception.
204+
in the stream, ``__next__()`` must raise the ``StopIteration`` exception.
205205
Iterators don't have to be finite, though; it's perfectly reasonable
206206
to write an iterator that produces an infinite stream of data.
207+
The built-in ``next()`` function is normally used to call the iterator's
208+
``__next__()`` method.
207209

208210
The built-in ``iter()`` function takes an arbitrary object and tries
209211
to return an iterator that will return the object's contents or
@@ -218,13 +220,13 @@ You can experiment with the iteration interface manually::
218220
>>> it = iter(L)
219221
>>> print it
220222
<iterator object at 0x8116870>
221-
>>> it.next()
223+
>>> next(it)
222224
1
223-
>>> it.next()
225+
>>> next(it)
224226
2
225-
>>> it.next()
227+
>>> next(it)
226228
3
227-
>>> it.next()
229+
>>> next(it)
228230
Traceback (most recent call last):
229231
File "<stdin>", line 1, in ?
230232
StopIteration
@@ -271,7 +273,7 @@ won't return either.
271273
Note that you can only go forward in an iterator; there's no way to
272274
get the previous element, reset the iterator, or make a copy of it.
273275
Iterator objects can optionally provide these additional capabilities,
274-
but the iterator protocol only specifies the ``next()`` method.
276+
but the iterator protocol only specifies the ``__next__()`` method.
275277
Functions may therefore consume all of the iterator's output, and if
276278
you need to do something different with the same stream, you'll have
277279
to create a new iterator.
@@ -485,21 +487,21 @@ outputs the value of ``i``, similar to a ``return``
485487
statement. The big difference between ``yield`` and a
486488
``return`` statement is that on reaching a ``yield`` the
487489
generator's state of execution is suspended and local variables are
488-
preserved. On the next call to the generator's ``.next()`` method,
490+
preserved. On the next call ``next(generator)``,
489491
the function will resume executing.
490492

491493
Here's a sample usage of the ``generate_ints()`` generator::
492494

493495
>>> gen = generate_ints(3)
494496
>>> gen
495497
<generator object at 0x8117f90>
496-
>>> gen.next()
498+
>>> next(gen)
497499
0
498-
>>> gen.next()
500+
>>> next(gen)
499501
1
500-
>>> gen.next()
502+
>>> next(gen)
501503
2
502-
>>> gen.next()
504+
>>> next(gen)
503505
Traceback (most recent call last):
504506
File "stdin", line 1, in ?
505507
File "stdin", line 2, in generate_ints
@@ -521,7 +523,7 @@ You could achieve the effect of generators manually by writing your
521523
own class and storing all the local variables of the generator as
522524
instance variables. For example, returning a list of integers could
523525
be done by setting ``self.count`` to 0, and having the
524-
``next()`` method increment ``self.count`` and return it.
526+
``__next__()`` method increment ``self.count`` and return it.
525527
However, for a moderately complicated generator, writing a
526528
corresponding class can be much messier.
527529

@@ -583,7 +585,7 @@ use parentheses when there's an operation, as in ``val = (yield i)
583585
Values are sent into a generator by calling its
584586
``send(value)`` method. This method resumes the
585587
generator's code and the ``yield`` expression returns the specified
586-
value. If the regular ``next()`` method is called, the
588+
value. If the regular ``__next__()`` method is called, the
587589
``yield`` returns ``None``.
588590

589591
Here's a simple counter that increments by 1 and allows changing the
@@ -604,18 +606,18 @@ value of the internal counter.
604606
And here's an example of changing the counter:
605607

606608
>>> it = counter(10)
607-
>>> print it.next()
609+
>>> print next(it)
608610
0
609-
>>> print it.next()
611+
>>> print next(it)
610612
1
611613
>>> print it.send(8)
612614
8
613-
>>> print it.next()
615+
>>> print next(it)
614616
9
615-
>>> print it.next()
617+
>>> print next(it)
616618
Traceback (most recent call last):
617619
File ``t.py'', line 15, in ?
618-
print it.next()
620+
print next(it)
619621
StopIteration
620622

621623
Because ``yield`` will often be returning ``None``, you

Doc/lib/libcollections.tex

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ \subsubsection{Recipes \label{deque-recipes}}
174174
while pending:
175175
task = pending.popleft()
176176
try:
177-
yield task.next()
177+
yield next(task)
178178
except StopIteration:
179179
continue
180180
pending.append(task)
@@ -315,12 +315,12 @@ \subsubsection{\class{defaultdict} Examples \label{defaultdict-examples}}
315315

316316
The function \function{int()} which always returns zero is just a special
317317
case of constant functions. A faster and more flexible way to create
318-
constant functions is to use \function{itertools.repeat()} which can supply
318+
constant functions is to use a lambda function which can supply
319319
any constant value (not just zero):
320320

321321
\begin{verbatim}
322322
>>> def constant_factory(value):
323-
... return itertools.repeat(value).next
323+
... return lambda: value
324324
>>> d = defaultdict(constant_factory('<missing>'))
325325
>>> d.update(name='John', action='ran')
326326
>>> '%(name)s %(action)s to %(object)s' % d

Doc/lib/libcsv.tex

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -487,8 +487,8 @@ \subsection{Examples\label{csv-examples}}
487487
def __iter__(self):
488488
return self
489489
490-
def next(self):
491-
return self.reader.next().encode("utf-8")
490+
def __next__(self):
491+
return next(self.reader).encode("utf-8")
492492
493493
class UnicodeReader:
494494
"""
@@ -500,8 +500,8 @@ \subsection{Examples\label{csv-examples}}
500500
f = UTF8Recoder(f, encoding)
501501
self.reader = csv.reader(f, dialect=dialect, **kwds)
502502
503-
def next(self):
504-
row = self.reader.next()
503+
def __next__(self):
504+
row = next(self.reader)
505505
return [unicode(s, "utf-8") for s in row]
506506
507507
def __iter__(self):

Doc/lib/libdis.tex

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -529,10 +529,10 @@ \subsection{Python Byte Code Instructions}
529529
\end{opcodedesc}
530530

531531
\begin{opcodedesc}{FOR_ITER}{delta}
532-
\code{TOS} is an iterator. Call its \method{next()} method. If this
533-
yields a new value, push it on the stack (leaving the iterator below
534-
it). If the iterator indicates it is exhausted \code{TOS} is
535-
popped, and the byte code counter is incremented by \var{delta}.
532+
\code{TOS} is an iterator. Call its \method{__next__()} method. If this
533+
yields a new value, push it on the stack (leaving the iterator below it). If
534+
the iterator indicates it is exhausted \code{TOS} is popped, and the byte code
535+
counter is incremented by \var{delta}.
536536
\end{opcodedesc}
537537

538538
%\begin{opcodedesc}{FOR_LOOP}{delta}

Doc/lib/libexcs.tex

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,8 @@ \section{Built-in Exceptions}
265265
\end{excdesc}
266266

267267
\begin{excdesc}{StopIteration}
268-
Raised by an iterator's \method{next()} method to signal that there
269-
are no further values.
268+
Raised by builtin \function{next()} and an iterator's \method{__next__()}
269+
method to signal that there are no further values.
270270
This is derived from \exception{Exception} rather than
271271
\exception{StandardError}, since this is not considered an error in
272272
its normal application.

Doc/lib/libfuncs.tex

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -342,14 +342,12 @@ \section{Built-in Functions \label{built-in-funcs}}
342342
\end{funcdesc}
343343

344344
\begin{funcdesc}{enumerate}{iterable}
345-
Return an enumerate object. \var{iterable} must be a sequence, an
346-
iterator, or some other object which supports iteration. The
347-
\method{next()} method of the iterator returned by
348-
\function{enumerate()} returns a tuple containing a count (from
349-
zero) and the corresponding value obtained from iterating over
350-
\var{iterable}. \function{enumerate()} is useful for obtaining an
351-
indexed series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2,
352-
seq[2])}, \ldots.
345+
Return an enumerate object. \var{iterable} must be a sequence, an iterator, or
346+
some other object which supports iteration. The \method{__next__()} method of
347+
the iterator returned by \function{enumerate()} returns a tuple containing a
348+
count (from zero) and the corresponding value obtained from iterating over
349+
\var{iterable}. \function{enumerate()} is useful for obtaining an indexed
350+
series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2, seq[2])}, \ldots.
353351
\versionadded{2.3}
354352
\end{funcdesc}
355353

@@ -615,7 +613,7 @@ \section{Built-in Functions \label{built-in-funcs}}
615613
support either of those protocols, \exception{TypeError} is raised.
616614
If the second argument, \var{sentinel}, is given, then \var{o} must
617615
be a callable object. The iterator created in this case will call
618-
\var{o} with no arguments for each call to its \method{next()}
616+
\var{o} with no arguments for each call to its \method{__next__()}
619617
method; if the value returned is equal to \var{sentinel},
620618
\exception{StopIteration} will be raised, otherwise the value will
621619
be returned.
@@ -695,6 +693,12 @@ \section{Built-in Functions \label{built-in-funcs}}
695693
\versionchanged[Added support for the optional \var{key} argument]{2.5}
696694
\end{funcdesc}
697695

696+
\begin{funcdesc}{next}{iterator\optional{, default}}
697+
Retrieve the next item from the \var{iterable} by calling its
698+
\method{__next__()} method. If \var{default} is given, it is returned if the
699+
iterator is exhausted, otherwise \exception{StopIteration} is raised.
700+
\end{funcdesc}
701+
698702
\begin{funcdesc}{object}{}
699703
Return a new featureless object. \class{object} is a base
700704
for all new style classes. It has the methods that are common

Doc/lib/libitertools.tex

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -164,16 +164,16 @@ \subsection{Itertool functions \label{itertools-functions}}
164164
self.tgtkey = self.currkey = self.currvalue = xrange(0)
165165
def __iter__(self):
166166
return self
167-
def next(self):
167+
def __next__(self):
168168
while self.currkey == self.tgtkey:
169-
self.currvalue = self.it.next() # Exit on StopIteration
169+
self.currvalue = next(self.it) # Exit on StopIteration
170170
self.currkey = self.keyfunc(self.currvalue)
171171
self.tgtkey = self.currkey
172172
return (self.currkey, self._grouper(self.tgtkey))
173173
def _grouper(self, tgtkey):
174174
while self.currkey == tgtkey:
175175
yield self.currvalue
176-
self.currvalue = self.it.next() # Exit on StopIteration
176+
self.currvalue = next(self.it) # Exit on StopIteration
177177
self.currkey = self.keyfunc(self.currvalue)
178178
\end{verbatim}
179179
\versionadded{2.4}
@@ -227,7 +227,7 @@ \subsection{Itertool functions \label{itertools-functions}}
227227
def imap(function, *iterables):
228228
iterables = map(iter, iterables)
229229
while True:
230-
args = [i.next() for i in iterables]
230+
args = [next(i) for i in iterables]
231231
if function is None:
232232
yield tuple(args)
233233
else:
@@ -253,11 +253,11 @@ \subsection{Itertool functions \label{itertools-functions}}
253253
def islice(iterable, *args):
254254
s = slice(*args)
255255
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
256-
nexti = it.next()
256+
nexti = next(it)
257257
for i, element in enumerate(iterable):
258258
if i == nexti:
259259
yield element
260-
nexti = it.next()
260+
nexti = next(it)
261261
\end{verbatim}
262262

263263
If \var{start} is \code{None}, then iteration starts at zero.
@@ -276,7 +276,7 @@ \subsection{Itertool functions \label{itertools-functions}}
276276
def izip(*iterables):
277277
iterables = map(iter, iterables)
278278
while iterables:
279-
result = [it.next() for it in iterables]
279+
result = [next(it) for it in iterables]
280280
yield tuple(result)
281281
\end{verbatim}
282282

@@ -297,7 +297,7 @@ \subsection{Itertool functions \label{itertools-functions}}
297297
from each iterator in-turn, but the process ends when one of the iterators
298298
terminates. This leaves the last fetched values in limbo (they cannot be
299299
returned in a final, incomplete tuple and they are cannot be pushed back
300-
into the iterator for retrieval with \code{it.next()}). In general,
300+
into the iterator for retrieval with \code{next(it)}). In general,
301301
\function{izip()} should only be used with unequal length inputs when you
302302
don't care about trailing, unmatched values from the longer iterables.
303303
\end{funcdesc}
@@ -360,7 +360,7 @@ \subsection{Itertool functions \label{itertools-functions}}
360360
def starmap(function, iterable):
361361
iterable = iter(iterable)
362362
while True:
363-
yield function(*iterable.next())
363+
yield function(*next(iterable))
364364
\end{verbatim}
365365
\end{funcdesc}
366366

@@ -393,7 +393,7 @@ \subsection{Itertool functions \label{itertools-functions}}
393393
item = data.pop(i)
394394
yield item
395395
it = iter(iterable)
396-
return (gen(it.next), gen(it.next))
396+
return (gen(it.__next__), gen(it.__next__))
397397
\end{verbatim}
398398

399399
Note, once \function{tee()} has made a split, the original \var{iterable}
@@ -556,10 +556,7 @@ \subsection{Recipes \label{itertools-recipes}}
556556
def pairwise(iterable):
557557
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
558558
a, b = tee(iterable)
559-
try:
560-
b.next()
561-
except StopIteration:
562-
pass
559+
next(b, None)
563560
return izip(a, b)
564561
565562
def grouper(n, iterable, padvalue=None):

Doc/lib/libstdtypes.tex

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -388,18 +388,17 @@ \section{Iterator Types \label{typeiter}}
388388
specialized forms. The specific types are not important beyond their
389389
implementation of the iterator protocol.
390390

391-
The intention of the protocol is that once an iterator's
392-
\method{next()} method raises \exception{StopIteration}, it will
393-
continue to do so on subsequent calls. Implementations that
394-
do not obey this property are deemed broken. (This constraint
395-
was added in Python 2.3; in Python 2.2, various iterators are
396-
broken according to this rule.)
391+
The intention of the protocol is that once an iterator's \method{__next__()}
392+
method raises \exception{StopIteration}, it will continue to do so on subsequent
393+
calls. Implementations that do not obey this property are deemed broken. (This
394+
constraint was added in Python 2.3; in Python 2.2, various iterators are broken
395+
according to this rule.)
397396

398-
Python's generators provide a convenient way to implement the
399-
iterator protocol. If a container object's \method{__iter__()}
400-
method is implemented as a generator, it will automatically
401-
return an iterator object (technically, a generator object)
402-
supplying the \method{__iter__()} and \method{next()} methods.
397+
Python's generators provide a convenient way to implement the iterator protocol.
398+
If a container object's \method{__iter__()} method is implemented as a
399+
generator, it will automatically return an iterator object (technically, a
400+
generator object) supplying the \method{__iter__()} and \method{__next__()}
401+
methods.
403402

404403

405404
\section{Sequence Types ---
@@ -1587,17 +1586,17 @@ \section{File Objects
15871586
with a real file, this method should \emph{not} be implemented.}
15881587
\end{methoddesc}
15891588

1590-
\begin{methoddesc}[file]{next}{}
1589+
\begin{methoddesc}[file]{__next__}{}
15911590
A file object is its own iterator, for example \code{iter(\var{f})} returns
15921591
\var{f} (unless \var{f} is closed). When a file is used as an
15931592
iterator, typically in a \keyword{for} loop (for example,
1594-
\code{for line in f: print line}), the \method{next()} method is
1593+
\code{for line in f: print line}), the \method{__next__()} method is
15951594
called repeatedly. This method returns the next input line, or raises
15961595
\exception{StopIteration} when \EOF{} is hit. In order to make a
15971596
\keyword{for} loop the most efficient way of looping over the lines of
1598-
a file (a very common operation), the \method{next()} method uses a
1597+
a file (a very common operation), the \method{__next__()} method uses a
15991598
hidden read-ahead buffer. As a consequence of using a read-ahead
1600-
buffer, combining \method{next()} with other file methods (like
1599+
buffer, combining \method{__next__()} with other file methods (like
16011600
\method{readline()}) does not work right. However, using
16021601
\method{seek()} to reposition the file to an absolute position will
16031602
flush the read-ahead buffer.

Doc/lib/sqlite3/executemany_1.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def __init__(self):
77
def __iter__(self):
88
return self
99

10-
def next(self):
10+
def __next__(self):
1111
if self.count > ord('z'):
1212
raise StopIteration
1313
self.count += 1

0 commit comments

Comments
 (0)