In principle it is easy enough to write a wrapper for iterators, that allows arbitrary look-ahead, and some questions have been dedicated to that (e.g. Using lookahead with generators).
However, given that pretty much every non-trivial file-parsing would profit from such a facility, it seems like too obvious an oversight for the standard library; Is there really no builtin or standard-library mechanism, that would allow peeking?
Specifically, I usually need peeking that works across function calls: A subfunction should be able to inspect an arbitrary number of upcoming elements, without removing them from the iterator – essentially a queue data type, where the elements are taken lazily from an iterator.
In some cases, collections.deque
or itertools.tee
can be used to construct workarounds. For the sake of code-readability, they are however unfavorable.