[Python-ideas] Introduce collections.Reiterable

Nick Coghlan ncoghlan at gmail.com
Thu Sep 19 10:32:52 CEST 2013

(Grr, why is Google Groups so broken? :P)

My question would be, does the new class add anything that isn't
already covered by:

    isinstance(c, Iterable) and not isinstance(c, Iterator)


On 19 September 2013 18:23, Neil Girdhar <mistersheik at gmail.com> wrote:
> This is an idea I've wanted for a while:
> When I call functions that accept an iterable, I often have to check whether
> the function iterates over the iterable once or more than once.  If it
> iterates more than once, I must not pass a generator, but rather cast to a
> list.  Otherwise, the second iteration through the generator will be empty
> as the first has exhausted it completely.
> It would be nice to introduce an abstract base class in collections (docs)
> between Iterable and Sequence.  Right now, Sequence inherits from Iterable.
> I propose having Sequence inherit from Reiterable, which in turn, inherits
> from Iterable.  All sequences are reiterable, whereas generators are not.
> However, views in sets and dictionaries, and numpy arrays are examples of
> Reiterables that are not Sequences. Having such an abstract base class would
> be useful for debugging in its own right.
> Also, functions that iterate twice over an iterable can check to make sure
> the iterable is "re-iterable" using isinstance (the standard approach as per
> pep 3119).  But, better yet, itertools could add two functions: auto_tee,
> which takes an iterable "I" as its parameter, and an integer n.  If it is
> not a reiterable, it calls tee and returns n iterables independently capable
> of iterating "I".  If it is reiterable, it returns [I] * n.  This way, the
> client code can do whatever is easiest and the target code can call auto_tee
> if necessary.  auto_list could do the same sort of thing, but omitting the
> copy that would normally be incurred if a list were passed in.
> Maybe this is less useful than I once thought since I've gotten by without
> it, but I just wanted to throw the idea out there in case it clicks for
> someone else.
> Neil
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list