[Python-ideas] Introduce collections.Reiterable

Ethan Furman ethan at stoneleaf.us
Mon Sep 23 01:55:49 CEST 2013


On 09/22/2013 04:46 PM, Steven D'Aprano wrote:
>
> The sequence protocol allows one to write a lazily generated,
> potentially infinite sequence that still allows random access to items.
> Here's a toy example:
>
>
> py> class Squares:
> ...     def __getitem__(self, index):
> ...         return index**2
> ...
> py> for sq in Squares():
> ...     if sq > 9: break
> ...     print(sq)
> ...
> 0
> 1
> 4
> 9
>
>
> Because it's infinite, there's no value that __len__ can return, and no
> need for a __len__. Because it supports random access to items, writing
> this as an iterator with __next__ is inappropriate. Writing *both* is
> unnecessary, and complicates the class for no benefit. As written,
> Squares is naturally thread-safe -- two threads can iterate over the
> same Squares object without interfering.

Nice example.  :)

--
~Ethan~


More information about the Python-ideas mailing list