[Python-ideas] Assignments in list/generator expressions

Stephen J. Turnbull stephen at xemacs.org
Tue Apr 12 10:01:15 CEST 2011

Greg Ewing writes:
 > Nick Coghlan wrote:
 > > This one is tricky, since the assignment is *after* the for loop, but
 > > *before* the filter condition.

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.  I would
expect you will need a restriction against using a "given"-bound
variable in another "given" clause, so syntactically I don't think it
matters where in the expression it appears.

 > That's why I like the 'letting' form, because it both
 > reads correctly and matches the order of execution.
 >    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.  This is way worse than
"x if y else z", which awkward but I can't parse it any way other than
"x (if y), else z".  For some reason "given" binds the expression a
lot more tightly than "letting" does in my dialect.  I do prefer the
"given" at the end, but putting it in the middle doesn't bother me.

It's not that I couldn't get used to it, but I suspect I would never
learn to like it.  I hope others feel the same way.<wink>

More information about the Python-ideas mailing list