On Dec 6, 2019, at 16:44, Steven D'Aprano <st...@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.

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HERNHZV6JFCBNX56FL6I37CEBJGLUGOT/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to