[Python-ideas] Assignments in list/generator expressions

Bruce Leban bruce at leapyear.org
Mon Apr 11 04:51:24 CEST 2011


On Sun, Apr 10, 2011 at 6:42 PM, Eugene Toder <eltoder at gmail.com> wrote:

> Local assignment simply provides a more direct way of doing it, and to
> me a more direct way is easier to read.


I don't think there's going to be consensus that sticking additional
assignment in the middle of a generator expression makes it more readable.
The expressions you're talking about really are conceptually nested and
you're trying to eliminate/hide that. Let me throw out an alternative. In
these expressions there's redundant boilerplate ("x for x in ...") when what
we're really doing is a simple filter or map across the sequence. In these
examples, {sequence} stands in for both the sequence being iterated and the
value from the sequence being operated on.

( for {seq} + 1 )   =>  ( x + 1 for x in seq )
( for f({seq}) )    =>  ( f(x) for x in seq )
( if {seq} > 1 }    =>  ( x for x in seq if x > 1 )

But here's the catch. While I would like a simpler way to express these
idioms, I don't think these offer enough of an advantage. And I think that
when you start to nest them it quickly becomes unreadable:


(y for y in (f(x) for x in xs) if y)  =>  (if {(for f({xs})})


And {} looks  a bit too much like () for my taste -- I find that trailing
})}) particularly hard to read.

So why offer this proposal? I think there's a natural tendency to try to
come up with terse expressions for common idioms. But they don't add power
and they make the language less approachable. I think terseness is sometimes
the opposite of readability. In C# the lambda syntax is terse and I find it
unreadable if written without line breaks:

f(x, y + 1, x => x + 1, y + 1)

vs.

f(x, y + 1,
  x => x + 1,
  y + 1)


--- Bruce
*New! *Puzzazz newsletter: http://j.mp/puzzazz-news-2011-04 including April
Fools!
*New!** *Blog post:
http://www.vroospeak.com/2011/04/march-gets-more-madness-next-year.html April
Fools!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110410/9f7f8944/attachment.html>


More information about the Python-ideas mailing list