0

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.

kdb
  • 4,098
  • 26
  • 49

1 Answers1

1

No.


I often find myself using the pairwise Recipe to lookahead...

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for item, peek in pairwise(iterable):
    ...

Or simply turn your iterable into a Sequence (if it's not already) and use indexed lookups.

for index, item in enumerate(sequence):
    try:
        peek = sequence[index+1]
    except IndexError:
        peek = None
Sebastian Loehner
  • 1,302
  • 7
  • 5