[Python-Dev] PEP 479: Change StopIteration handling inside generators
Ron Adam
ron3200 at gmail.com
Sun Nov 23 01:51:22 CET 2014
On 11/22/2014 06:20 PM, Chris Angelico wrote:
> 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.
Just didn't think it through quite well enough. But you are correct, that
would be a generator expression.
One less case to worry about. :-)
> 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:
Right, the list.append() should be a yield(expr).
> 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.)
That's fine too.
The real question is how much breakage would such a change make? That will
probably need a patch in order to test it out.
Cheers,
Ron
More information about the Python-Dev
mailing list