[Python-ideas] Introduce collections.Reiterable
mistersheik at gmail.com
Thu Sep 19 11:58:38 CEST 2013
Sorry, never mind, the documentation is clear. I got caught up with
collections.abc page and didn't click through. At least I have Antoine's
code now to use in my project whether it gets added to the standard library
or not :)
On Thu, Sep 19, 2013 at 5:38 AM, Neil Girdhar <mistersheik at gmail.com> wrote:
> First of all, that's amazing and exactly what I was looking for.
> Second, sorry Nick, I guess we were talking past each other and I didn't
> understand what you were getting at. From the collections.abc
> documentation, I imagined that subclasses are more restricted and therefore
> can do more than their superclasses. However, as you were trying to tell
> me things that are "Iterators" (and thus also Iterable) can do *less* than
> things that are merely Iterable. The former cannot be iterated over twice.
> If I'm understanding this correctly, would it be nice if the
> documentation then made this promise (as I don't believe it does)?
> On Thu, Sep 19, 2013 at 5:30 AM, Antoine Pitrou <solipsis at pitrou.net>wrote:
>> 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.
>> Python-ideas mailing list
>> Python-ideas at python.org
>> You received this message because you are subscribed to a topic in the
>> Google Groups "python-ideas" group.
>> To unsubscribe from this topic, visit
>> To unsubscribe from this group and all its topics, send an email to
>> python-ideas+unsubscribe at googlegroups.com.
>> For more options, visit https://groups.google.com/groups/opt_out.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas