classification
Title: Second argument to iterator.next not described
Type: behavior Stage: resolved
Components: Documentation Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: docs@python Nosy List: Andrew Black, docs@python, rahul-kumi, remi.lapeyre, rhettinger
Priority: normal Keywords:

Created on 2020-05-09 15:00 by Andrew Black, last changed 2020-05-22 13:14 by rhettinger. This issue is now closed.

Messages (3)
msg368525 - (view) Author: Andrew Black (Andrew Black) Date: 2020-05-09 15:00
The documentation for the built-in function next (which calls the __next__ method on an iterator) discusses its behavior when the iterator is exhausted.
It talks about the StopIteration exception.  However, it does not say anything about calling next with two arguments.  See the library documentation at https://docs.python.org/3/library/stdtypes.html#iterator-types

My impression was that the presence of the second argument would suppress the StopIteration exception; instead next would return the value of the second argument.  That is the way that list iterators behave, for example.  This behavior should be documented.
msg368527 - (view) Author: RĂ©mi Lapeyre (remi.lapeyre) * Date: 2020-05-09 15:20
It's documented here: https://docs.python.org/3/library/functions.html#next
msg368529 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2020-05-09 16:31
The next() function has a different signature than the __next__() method.  The former takes one or two arguments.  That latter only takes one.

    >>> it = iter('abcde')
    >>> next(it)
    'a'
    >>> next(it, 'default')
    'b'
    >>> it.__next__()
    'c'
    >>> it.__next__('default')
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        it.__next__('default')
    TypeError: expected 0 arguments, got 1
History
Date User Action Args
2020-05-22 13:14:50rhettingersetstatus: open -> closed
resolution: not a bug
stage: resolved
2020-05-22 09:15:20rahul-kumisetnosy: + rahul-kumi
2020-05-09 16:31:11rhettingersetnosy: + rhettinger
messages: + msg368529
2020-05-09 15:20:33remi.lapeyresetnosy: + remi.lapeyre
messages: + msg368527
2020-05-09 15:00:43Andrew Blackcreate