Unfortunately "else break" also kind of falls flat on its face when you consider it's being used in context of an expression.

Shane Green 
408-692-4666 | shane@umbrellacode.com

On Jan 29, 2013, at 2:44 AM, Nick Coghlan <ncoghlan@gmail.com> wrote:

On Tue, Jan 29, 2013 at 11:30 AM, Steven D'Aprano <steve@pearwood.info> wrote:
Why would it translate that way? That would be a silly decision to make.
Python can decide on the semantics of a while clause in a comprehension in
whatever way makes the most sense, not necessarily according to some
mechanical, nonsensical translation.

Terry is correct: comprehensions are deliberately designed to have the
exact same looping semantics as the equivalent statements flattened
out into a single line, with the innermost expression lifted out of
the loop body and placed in front. This then works to arbitrarily deep
nesting levels. The surrounding syntax (parentheses, brackets, braces,
and whether or not there is a colon present in the main expression)
then governs what kind of result you get (generator-iterator, list,
set, dict).

For example in:

  (x, y, z for x in a if x for y in b if y for z in c if z)
  [x, y, z for x in a if x for y in b if y for z in c if z]
  {x, y, z for x in a if x for y in b if y for z in c if z}
  {x: y, z for x in a if x for y in b if y for z in c if z}

The looping semantics of these expressions are all completely defined
by the equivalent statements:

   for x in a:
       if x:
           for y in b:
               if y:
               for z in c:
                   if z:

(modulo a few name lookup quirks if you're playing with class scopes)

Any attempt to change that fundamental equivalence between
comprehensions and the corresponding statements has basically zero
chance of getting accepted through the PEP process.

The only remotely plausible proposal I've seen in this thread is the
"else break" on the filter conditions, because that *can* be mapped
directly to the statement form in order to accurately describe the
intended semantics. However, it would fail the "just use
itertools.takewhile or a custom iterator, that use case isn't common
enough to justify dedicated syntax". The conceptual basis of Python's
comprehensions in mathematical set notation would likely also play a
part in rejecting an addition that requires an inherently procedural


Nick Coghlan   |   ncoghlan@gmail.com   |   Brisbane, Australia
Python-ideas mailing list