if iter(iterator) is iterator

Chris Angelico rosuav at gmail.com
Sun Nov 13 17:04:50 EST 2016


On Mon, Nov 14, 2016 at 8:57 AM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Antoon Pardon wrote:
>
>> def bar(iterator):
>>     if iter(iterator) is iterator:
>>         ...
>
>
> That's a way of finding out whether you can safely iterate
> over something more than once. If the object is already an
> iterator, applying iter() to it will return the same
> object, and iterating over it will consume it.

Not strictly true. There's no guarantee that something that yields new
iterators is actually reiterable. And even if it is, there's no
guarantee that it'll yield the same values.

ChrisA



More information about the Python-list mailing list