[Python-ideas] Introduce collections.Reiterable

Antoine Pitrou solipsis at pitrou.net
Thu Sep 19 11:30:47 CEST 2013

Le Thu, 19 Sep 2013 04:59:35 -0400,
Neil Girdhar <mistersheik at gmail.com> a
écrit :
> Well, generators are iterable, but if you write a function like:
> def f(s):
>      for x in s:
>              do_something(x)
>      for x in s:
>              do_something_else(x)
> 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
            return iter(self.master)

def gen():
    yield from "ghi"

for arg in ("abc", iter("def"), gen()):
    it = Reiterable(arg)

I don't know if that would be useful as part of the stdlib.



More information about the Python-ideas mailing list