[Python-ideas] Introduce collections.Reiterable

Terry Reedy tjreedy at udel.edu
Thu Sep 19 12:21:25 CEST 2013


On 9/19/2013 5:30 AM, Antoine Pitrou wrote:

>> x should not be a generator.  I am proposing adding a function to
>> itertools like auto_reiterable that would take s and give you an
>> reiterable in the most efficient way possible.
>
> Try the following:
>
>
> import collections
> import itertools
>
>
> class Reiterable:
>
>      def __init__(self, it):
>          self.need_cloning = isinstance(it, collections.Iterator)
>          assert self.need_cloning or isinstance(it, collections.Iterable)
>          self.master = it
>
>      def __iter__(self):
>          if self.need_cloning:
>              self.master, it = itertools.tee(self.master)
>              return it
>          else:
>              return iter(self.master)
>
> def gen():
>      yield from "ghi"
>
> for arg in ("abc", iter("def"), gen()):
>      it = Reiterable(arg)
>      print(list(it))
>      print(list(it))
>      print(list(it))
>
>
> I don't know if that would be useful as part of the stdlib.

A slight problem is that there is no guaranteed that a non-iterator 
iterable is re-iterable.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list