Python: Why should I use next() and not obj.next()

2019-01-17 20:37发布

问题:

Python 2.6 introduced a next function.

Why was this necessary? One could always type obj.next() instead of next(obj).

Is the latter more pythonic?

回答1:

PEP 3114 describes this change. An excerpt about the motivation:

This PEP proposes that the next method be renamed to __next__, consistent with all the other protocols in Python in which a method is implicitly called as part of a language-level protocol, and that a built-in function named next be introduced to invoke __next__ method, consistent with the manner in which other protocols are explicitly invoked.

Be sure to read this PEP for more interesting details.

As for why you want to use the next built-in: one good reason is that the next method disappears in Python 3, so for portability it's better to start using the next built-in as soon as possible.



回答2:

next(iterator[, default])

Retrieve the next item from the iterator by calling its next()(__next__() in python 3) method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

You get the default option.



回答3:

Apart from the obvious additional functionality, it also looks better when used together with generator expressions. Compare

(x for x in lst if x > 2).next()

to

next(x for x in lst if x > 2)

The latter is a lot more consistent with the rest of Python's style, IMHO.