if iter(iterator) is iterator

Chris Angelico rosuav at gmail.com
Sun Nov 13 15:19:14 EST 2016


On Mon, Nov 14, 2016 at 7:02 AM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> Some time ago I read a text or saw a video on iterators and one thing
> I remember from it, is that you should do something like the following
> when working with iterators, to avoid some pitt falls.
>
> def bar(iterator):
>     if iter(iterator) is iterator:
>         ...
>
> However I can't relocate it and can't remember the what and how anymore.
> Does anyone know what this is about?

That's how you distinguish an iterator from other iterables. An
iterable is something you can call iter() on; an iterator is required
to specifically return _itself_.

What you do with that information, though, depends on the function. In
a lot of cases, you shouldn't care - if you need an iterator, just
"iterator = iter(iterator)" at the top and move on.

ChrisA



More information about the Python-list mailing list