1

I'm searching for a "pythonic" way to assert the type of the first element in an iterable.

For example if i have the following list:

l = [(1,2,3), (4,5,6), ...]

And a function which it is passed into, i can simply do:

def foo(l):
    assert isinstance(l[0], tuple)
    ...

Now i'm searching for something similar to this that works with iterators as well, but doesn't load the whole list into ram. I can try:

def foo(it):
    assert isinstance(next(it), tuple)
    ...

it = iter(l)
foo(it)

but this obviously modifies the state of the iterator in the assertion.

Is there an easy way to peek at the first element of an iterator without modifying it?

Jörn Hees
  • 3,338
  • 22
  • 44
  • thanks, didn't find that dup :-/ but using `itertools.chain` as in their answer or `itertools.tee` as in mine below is kind of the same... – Jörn Hees May 21 '15 at 15:13
  • FYI I found it by searching *"Python peek iterator"* - see also http://code.activestate.com/recipes/577361-peek-ahead-an-iterator/ – jonrsharpe May 21 '15 at 15:14
  • yeah, i was too focused on "assert first element of iterator", i guess... i'll leave this for other people to find. – Jörn Hees May 21 '15 at 15:16

1 Answers1

2

My current (as i find ugly) solution is:

from itertools import tee

def foo(it):
    if __debug__:
        it1, it2 = tee(it, 2)
        assert isinstance(next(it1), tuple)
        it = it2
    ...

Is there a better / cooler way to peek at the first element that i'm not aware of?

Jörn Hees
  • 3,338
  • 22
  • 44