[Python-ideas] Introduce collections.Reiterable

Antoine Pitrou solipsis at pitrou.net
Thu Sep 19 12:26:30 CEST 2013


Le Thu, 19 Sep 2013 06:21:25 -0400,
Terry Reedy <tjreedy at udel.edu> a écrit :
> 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.

Any useful examples?

Regards

Antoine.




More information about the Python-ideas mailing list