[Python-ideas] Introduce collections.Reiterable

Steven D'Aprano steve at pearwood.info
Tue Sep 24 03:37:04 CEST 2013


On Tue, Sep 24, 2013 at 10:04:03AM +0900, Stephen J. Turnbull wrote:
> Neil Girdhar writes:
> 
>  > If infinite sequences are so common, it might be better to add a
>  > collections.abc for them.
> 
> I suspect this falls under the "not every 3-line function" clause,
> because it would really require a PEP to get right (changes to
> builtins like list and dict would be needed, IIUC).

A lot of work for virtually no benefit. Besides, who said that infinite 
iterators are common? 

 
> Just inherit from Sequence and add a __len__ which returns a unique
> object (probably could be None, actually), and check for that private
> protocol yourself.

Alas, that doesn't work.

py> class X:
...     def __len__(self):
...         return None
...
py> x = X()
py> len(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object cannot be interpreted as an integer


If you care about infinite iterators, you can add your own "isinfinite" 
flag on them. Personally, I wouldn't bother. I just consider this a case 
for programming by contract: unless the function you are calling 
promises to be safe with infinite iterators, you should not use them.



-- 
Steven


More information about the Python-ideas mailing list