[Python-ideas] PEP on yield-from: throw example

George Sakkis george.sakkis at gmail.com
Mon Feb 16 03:25:27 CET 2009

On Sun, Feb 15, 2009 at 2:41 PM, Bruce Frederiksen <dangyogi at gmail.com> wrote:

> I to do several posts, one on each item above in
> an attempt to demonstrate what we're talking about here.

Thanks for the examples, they gave some good idea of what we're
*really* talking about :)

> So what starts out conceptually simple, ends up more complicated and error
> prone that I had expected; and the reason is that the for statement doesn't
> support these new generators methods.  If it did, I would have:
> def process(generator, limit):
>   count = 1
>   for generator as name:     # new syntax doesn't break old code
>       if len(name) > 5:
>           print name, "qualifies"
>           count += 1
>           if count > limit: break
>       else:
>           raise DoesntQualify   # new for passes this to generator.throw
>   # new for remembers to call generator.close for me.

Backwards compatibility is not the (only) issue here. Calling
implicitly the extra generator methods is optional at best and
non-intuitive at worse. For close() it's usually desirable to be
called when a loop exits naturally, although that's debatable for
prematurely ended loops; the caller may still have a use for the
non-exhausted generator. For throw() however, I strongly disagree that
a raise statement in a loop should implicitly call generator.throw(),
regardless of what "for" syntax is used. When I read "raise
Exception", I expect the control to flow out of the current frame to
the caller, not in an unrelated frame of some generator. The only
viable option would perhaps be a new statement, say "throw Exception",
that distinguishes it clearly from raise.

> If I can't use yield from, and itertools.chain does work, and the for
> statement doesn't work, then I'm faced once again with having to code
> everything again myself:

As I said, I don't think that the for statement can or should be made
to "work", but would updating chain(), or all itertools.* for that
matter, so that they play well with the new methods solve most real
world cases ? If so, that's probably better than adding new syntax,
practicality-beats-purity and all that.


More information about the Python-ideas mailing list