[Python-ideas] A real life example of "given"
steve at pearwood.info
Thu May 31 08:24:21 EDT 2018
On Thu, May 31, 2018 at 04:44:18AM -0400, Neil Girdhar wrote:
> Yes, you're right. That's the ambiguity I mentioned in my last message.
> It's too bad because I want given for expressions and given for
Why? So far you haven't given (heh, pun intended) any examples of
something you can do better with "given for comprehensions" which isn't
either already doable or will be doable with assignment expressions
(regardless of spelling).
Earlier, I wrote:
"To showcase assignment expressions, we should be solving problems that
don't have a good solution now."
(I exclude "re-write your code as a for-loop statement" -- I consider
that a last resort, not the best solution.)
Now I realise that good solutions are in the eye of the beholder, but I
think we (mostly) agree that:
[process(x, 2*x, x**3) for obj in seq for x in [func(obj)]]
is a hacky solution for assignments in an expression. It works,
but it hardly speaks to the programmers intention. Whichever syntax we
use, an explicit assignment expression is better:
# verbose, Repeat Yourself syntax
[process(x given x = func(obj), 2*x, x**3) for obj in seq]
# concise, Don't Repeat Yourself syntax
[process(x := func(obj), 2*x, x**3) for obj in seq]
(I don't apologise for the editorial comments.)
Do you have an equally compelling example for your given-comprehension
syntax? I didn't think your example was obviously better than what we
can already do:
# calculate tx only once per x loop
[process(tx, y) for x in xs given tx = transform(x) for y in ys]
# existing solution
[process(tx, y) for tx in (transform(x) for x in xs) for y in yz]
Regardless of whether it is spelled := or given, I don't think that this
example is a compelling use-case for assignment expressions. I think
there are much better use-cases.
(E.g. avoiding cascades of nested if statements.)
More information about the Python-ideas