Python Iterables struggling using map() built-in

Chris Angelico rosuav at gmail.com
Sun Dec 7 18:50:39 EST 2014


On Mon, Dec 8, 2014 at 10:33 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> How would we re-write this to work in the future Python 3.7? Unless I have
> missed something, I think we could write it like this:
>
> def myzip37(*args):
>     iters = list(map(iter, args))
>     while iters:
>         try:
>             yield tuple([next(i) for i in iters])
>         except StopIteration:
>             return
>
> which I guess is not too horrible.

It's not horrible, and there are other ways it could be written too,
which also aren't horrible. Yes, it's not quite as short as the other
version; but more importantly, it's explicit about how StopIteration
affects it. It's clear that this exception, if raised by _any_ of the
iterators (even after consuming values from some of them, perhaps),
will silently terminate the generator.

The current behaviour favours a handful of cases like this, although
personally I think the termination of zip() is simply "this is what
happens if we have no code here, so let's document it" rather than
being something inherently ideal; the new behaviour favours the
debugging of many obscure cases and some less-obscure ones as well.
Most importantly, if you run the old version of myzip on Python 3.7,
you'll get an immediate and noisy RuntimeError when it terminates, and
you'll know exactly where to go fix stuff; if you run a buggy
generator on Python 3.4, you simply see no more results, without any
explanation of why. I'd rather debug the RuntimeError that can be
easily and trivially fixed in 99% of cases.

ChrisA



More information about the Python-list mailing list