[Python-ideas] Inline assignments using "given" clauses
Steven D'Aprano
steve at pearwood.info
Sat May 12 23:47:41 EDT 2018
On Sat, May 12, 2018 at 11:04:45PM -0400, Neil Girdhar wrote:
> Another benefit of given compared with := that I just thought of is this.
> Suppose you have a generator like
>
> (expression(f(x), y, z)
> for x in xs
> for y in ys(x)
> for z in zs(y))
>
> With given notation you can optimize:
>
> (expression(f_x, y, z)
> for x in xs
> given f_x = f(x)
> for y in ys(x)
> for z in zs(y))
>
> whereas with :=, you can't.
Is that legal syntax? You're splitting the "given" expression by
sticking the for clause in the middle of it. I don't think that will be
legal. It would be trying to split an ternary if:
(true_expr for x in xs if condition else false_expr for y in ys)
(true_expr if condition for x in xs else false_expr for y in ys)
But whether legal or not, Neil, you went on at length about how
professionals don't write code like this and such overly dense
comprehensions are only fit for competitions.
Now you want your cake and to eat it too:
"given is better, because it doesn't allow the awful
unreadable code that := gives; oh, and it's also better,
because it allows *this* awful unreadable code that :=
doesn't allow"
In any case, of course you can write this with := binding expression.
You just shouldn't do it:
(expression(f_x, y, z) for x in xs
for y in ys(x)
for z in zs(y)
if (f_x := f(x)) or True)
)
That's fine for mucking about, but I wouldn't do it for serious code.
Replacing the colon with "given f_x" doesn't change that.
--
Steve
More information about the Python-ideas
mailing list