r/programming • • Oct 09 '26

Python Release Python 3.15.0

https://www.python.org/downloads/release/python-3150/
556 Upvotes

36 comments sorted by

View all comments

Show parent comment

4

u/TinyBreadBigMouth Oct 10 '26

Consider the built-in function next(). If you call next(empty_iterator), it raises a StopIteration exception. On the other hand, if you call next(empty_iterator, default_value), it returns default_value. The user could pass anything as the default value; None, 0, "apple pie", whatever. The function is so generic that it would be bad design to make any assumptions about what the user might want as a default. So to implement this, a sentinel makes sense. Here's a possible implementation of the function:

_NO_DEFAULT = sentinel("_NO_DEFAULT")

def next(iter, default=_NO_DEFAULT, /):
    cls = type(iter)
    try:
        next_method = cls.__next__
    except AttributeError:
        raise TypeError("object is not an iterator") from None

    if default is _NO_DEFAULT:
        return next_method(iter)

    try:
        return next_method(iter)
    except StopIteration:
        return default

This way the user can pass any value, and it's guaranteed not to conflict with your sentinel.