[Python-ideas] Use the plus operator to concatenate iterators

Chris Angelico rosuav at gmail.com
Wed Aug 5 17:07:39 CEST 2015


On Thu, Aug 6, 2015 at 12:38 AM, Ed Kellett <edk141 at gmail.com> wrote:
> Python could do this for 1 and 2. 3 and 4 would be more difficult and
> ultimately require the author of the class to either inherit Iterator or
> write an __add__, but this might be eased a bit by having iter() wrap
> iterators that aren't instances of Iterator.
>

I offered a solution along these lines early in the thread -
effectively, you replace the builtin iter() with a class which wraps
the iterator in a way that allows addition as chaining. As far as I
can see, there *is no solution* that will accept arbitrary iterables
and meaningfully add them, so you're going to have to call iter() at
some point anyway. Why not use that as the hook that adds your new
method?

Note that a production-ready version of 'class iter' would need a
couple of additional features. One would be a "pass-through" mode -
have __new__ recognize that it's being called on an instance of
itself, and swiftly return it, thus making iter() idempotent. Another
would be supporting the iter(callable, sentinel) form, which shouldn't
be hard (just tweak __new__ and __init__ to allow two parameters).
There may be other requirements too, but probably nothing
insurmountable.

ChrisA


More information about the Python-ideas mailing list