[Python-ideas] Introduce collections.Reiterable

Terry Reedy tjreedy at udel.edu
Fri Sep 20 23:15:05 CEST 2013

On 9/20/2013 5:48 AM, Steven D'Aprano wrote:

> py> class Seq:
> ...     def __getitem__(self, index):
> ...             if 0 <= index < 5: return index+1000
> ...             raise IndexError
> ...
> py> s = Seq()
> py> isinstance(s, Iterable)
> False
> py> list(s)  # definitely iterable
> [1000, 1001, 1002, 1003, 1004]

I tested and iter() recognizes Seqs as iterables:

for i in iter(Seq()): print(i)
<same numbers as above>

It does, however, wrap them in an adaptor iterator class
 >>> type(iter(Seq()))
<class 'iterator'>
(which I was not really aware of before ;-) with proper __iter__ and 
__next__ methods
 >>> si is iter(si)
 >>> next(si)

So I agree that collections.Iterable is limited relative to glossary and 
Python definition. The glossary might say that the older __getitem__ 
protocol is semi-deprecated (it is no longer used directly) but is 
adapted for back compatibility. The problem with the protocol is that an 
iteration __getitem__ may be a fake __getitem__ in that it ignores 
*index* (because it calculates the next item from stored data). A 
fake-getitem iterable, if it also had __len__, would look like a 
Sequence even though it really is not, because it cannot be properly 
indexed. Such iterables are likely to not be reiterable.

Terry Jan Reedy

More information about the Python-ideas mailing list