[Python-ideas] Assignments in list/generator expressions

Stephen J. Turnbull stephen at xemacs.org
Wed Apr 13 04:27:08 CEST 2011


Greg Ewing writes:
 > Stephen J. Turnbull wrote:
 > 
 > > I don't have a problem with *reading* that, since you can't really
 > > win: "y" is used both before and after the "given" binding.
 > 
 > But

Turns out to be precisely why it's readable, I think.  But the "but"
is not the point.  The point is that (in my dialect) it *is* readable.

 > >  >    ys = [y for x in xs letting y = f(x) if y]
 > > 
 > > I'm sorry, but I read that three times and it parsed as "y gets
 > > undefined if it is false" every time.
 > 
 > In that case, would you prefer this?
 > 
 >    ys = [y for x in xs if y given y = f(x)]

Yes, very much.  I would also prefer

    ys = [y for x in xs given y = f(x) if y]

to the "letting" version, though that is harder to read (for me) than
the version with the assignment at the end of the expression.

I think the difference is that "let" is *local* to the comprehension
and local context will bind to it.  "given" is a meta-word, it refers
to something *outside* the comprehension, in my dialect.  So it is
undisturbed by the local context.

YMMV, that may be very specific to me.  As I say, I could probably get
used to "letting" if most people prefer it.  But in my personal usage,
"given" is clearly better.






More information about the Python-ideas mailing list