[Python-ideas] __iter__ implies __contains__?

Terry Reedy tjreedy at udel.edu
Mon Oct 3 05:54:58 CEST 2011


On 10/2/2011 6:00 PM, Greg Ewing wrote:

> It was probably a mistake not to make a clearer distinction
> between iterables and iterators back when the iterator
> protocol was designed, but we're stuck with it now.

It is extremely useful that iterators are iterables. The distinction 
needed between iterators and reiterable non-iterators is easy:
def reiterable(iterable):
   return hasattr(iterable, '__iter__') and not hasattr(iterable, 
'__next__')

In a context where one is going to iterate (and call __iter__ if 
present) more than once, only the second check is needed. Functions that 
need a reiterable can make that check at the start to avoid a possibly 
obscure message attendant on failure of reiteration.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list