[Python-Dev] PEP 572: Assignment Expressions (original) (raw)
Tim Peters tim.peters at gmail.com
Mon Apr 23 01:44:44 EDT 2018
- Previous message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Next message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[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 likeif ...: elif (m := re.match('(.):(.)', line)) and m.group(1) == m.group(2): 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 ;-)
- Previous message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Next message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]