[Python-Dev] PEP 479: Change StopIteration handling inside generators

Ron Adam ron3200 at gmail.com
Sun Nov 23 01:05:14 CET 2014



On 11/22/2014 04:23 PM, Chris Angelico wrote:
> On Sun, Nov 23, 2014 at 8:03 AM, Ron Adam<ron3200 at gmail.com>  wrote:
>>> >>Making comprehensions work more like generator expressions
>>> >>would, IMO, imply making the same change to all for loops: having a
>>> >>StopIteration raised by the body of the loop quietly terminate the
>>> >>loop.
>> >
>> >
>> >I'm not suggesting making any changes to generator expressions or for loops
>> >at all.  They would continue to work like they currently do.

> But if you're suggesting making list comps react to StopIteration
> raised by their primary expressions, then to maintain the
> correspondence between a list comp and its expanded form, for loops
> would have to change too.
> Or should that correspondence be broken, in
> that single-expression loop constructs become semantically different
> from statement loop constructs?


Se we have these...

      Tuple Comprehension  (...)
      List Comprehension  [...]
      Dict Comprehension  {...}  Colon make's it different from sets.
      Set Comprehension  {...}

I don't think there is any other way to create them. And they don't 
actually expand to any python code that is visible to a programmer.  They 
are self contained literal expressions for creating these few objects.

The expanded form you are referring to is just how we currently explain 
them.  And yes, we will need to alter how we currently explain 
Comprehensions a bit if this is done.


Here is what I think(?) list comps do currently.

      lst = [expr for items in itr if cond]

Is the same as.

      lst = []
      for x in itr:              # StopIteration  caught here.
          if cond:               # StopIteration  bubbles here.
              lst.append(expr)   # StopIteration  bubbles here.



And it would be changed to this...

     def comp_expression():
         for x in itr:          # StopIteration caught here.
             if cond:
                list.append(expr)

     # StopIteration from cond and expr caught here.
     lst = list(x for x in comp_expression())



So

    [expr for itr if cond]

Becomes a literal form of:

    list(expr for itr if cond)


And I believe that is how they are explained quite often. :-)


(Although It's not currently quite true, is it?)



Cheers,
    Ron



More information about the Python-Dev mailing list