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

Chris Angelico rosuav at gmail.com
Sun Nov 23 01:20:27 CET 2014


On Sun, Nov 23, 2014 at 11:05 AM, Ron Adam <ron3200 at gmail.com> wrote:
> 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.

Hmmm, there's no such thing as tuple comprehensions. Are you confusing
comprehension syntax (which has a 'for' loop in it) with
tuple/list/etc display, which doesn't?

lst = [1,2,3,4] # not a comprehension
even = [n*2 for n in lst] # comprehension

> 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.

Pretty much. It's done in a nested function (so x doesn't leak), but
otherwise, yes.

> 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())

That wouldn't quite work, but this would:

def <listcomp>():
    ret = []
    try:
        for x in itr:
            if cond:
                ret.append(x)
    except StopIteration:
        pass
    return ret
lst = <listcomp>()

(And yes, the name's syntactically illegal, but if you look at a
traceback, that's what is used.)

ChrisA


More information about the Python-Dev mailing list