
On Dec 6, 2019, at 16:44, Steven D'Aprano <steve@pearwood.info> wrote:
We could, I guess, eliminate the difference by adding the ability to peek ahead to the next value of an arbitrary iterator without consuming that value. This would have to be done by the interpreter, not in Python code,
You can easily wrap an iterator to make it peekable. Untested, off the top of my head on my phone: class Peekable(Iterator): _sentinel = object() def __init__(self, it): self._peek = self._sentinel self._it = iter(it) def __iter__(self): return self def __next__(self): if self._peek is not self._sentinel: result, self._peek = self._peek, self._sentinel return result return next(self._it) def peek(self): if self._peek is self._sentinel: self._peek = next(self._it) return self._peek You can easily add a default value for peek, a prepend method, an isempty method (or just call it __bool__), multiple levels of peek (use a deque, or tee), combine the last two to prepend multiple values (which is equivalent to chain, but sometimes more readable as a method), add indexing on top of the multi-peek, … There’s a version of this included in more-itertools, which I’ve used quite a few times. I don’t remember exactly which extra features it comes with, because usually I just want the basic peek.