# [Python-ideas] "given" vs ":=" in list comprehensions

Mark Dickinson dickinsm at gmail.com
Sun May 13 05:51:18 EDT 2018

```On Sun, May 13, 2018 at 1:34 AM, Andre Roberge <andre.roberge at gmail.com>
wrote:

> First example: single temporary assignment, done four different ways.
>
> 1) using :=
>
> real_roots = [ (-b/(2*a) + (D:= sqrt( (b/(2*a))**2 - c/a), -b/(2*a) - D)
>                          for a in range(10)
>                          for b in range(10)
>                          for c in range(10)
>                          if D >= 0]
>

Unless PEP 572 is doing something horribly magical, this doesn't look as
though it should work at all, so it may not be a good target for
comparisons with other syntax possibilities. I'd expect that the `D` name
lookup in the `if D >= 0` clause would occur before the (D := ...)
assignment in the target expression, resulting in an UnboundLocalError. (I
tried to check out Chris's reference implementation branch to verify, but
the compilation failed with a traceback.)

And a random mathematical nitpick: as a non-NaN result of a square root
operation, D will always satisfy D >= 0; for this use-case we want to check
the *argument* to the `sqrt` call for nonnegativity, rather than the
*result*. So I think the target statement for the comparison with other
syntaxes should look something like this instead:

real_roots = [
(-b/(2*a) + sqrt(D), -b/(2*a) - sqrt(D))
for a in range(1, 10)  # start at 1 to avoid division by zero
for b in range(10)
for c in range(10)
if (D := (b/(2*a))**2 - c/a) >= 0
]

Or possibly like this, using an extra assignment expression to avoid the
repeated computation of the square root:

real_roots = [
(-b/(2*a) + (s := sqrt(D)), -b/(2*a) - s)
for a in range(1, 10)
for b in range(10)
for c in range(10)
if (D := (b/(2*a))**2 - c/a) >= 0
]

Similar order-of-evaluation issues apply to example (8), and to the other
examples based on hypothetical syntax, depending on exactly how that syntax
is hypothesised to work.

--
Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180513/242974b4/attachment.html>
```