[Python-Dev] PEP 572: Assignment Expressions
Tim Peters
tim.peters at gmail.com
Mon Apr 23 01:44:44 EDT 2018
[Guido]
> In reality there often are other conditions being applied to the match for
> which `if expr as name` is inadequate. The simplest would be something like
>
> if ...:
> <something>
> elif (m := re.match('(.*):(.*)', line)) and m.group(1) == m.group(2):
> <whatever>
>
> And the match() call may not even be the first thing to check -- e.g. we
> could have
>
> elif line is not None and (m := re.match('(.*):(.*)', line)) and m.group(1) == m.group(2):
I find myself warming more to binding expressions the more I keep them
in mind while writing new code. And I think it may be helpful to
continue showing real examples where they would help.
Today's example: I happened to code this a few hours ago:
diff = x - x_base
if diff:
g = gcd(diff, n)
if g > 1:
return g
It's not really hard to follow, but two levels of nesting "feels
excessive", as does using the names "diff" and "g" three times each.
It's _really_ an "and" test: if the diff isn't 0 and gcd(diff, n) >
1, return the gcd. That's how I _thought_ of it from the start.
Which this alternative expresses directly:
if (diff := x - x_base) and (g := gcd(diff, n)) > 1:
return g
That's so Pythonic I could cry ;-)
More information about the Python-Dev
mailing list