[Python-Dev] PEP 572: Assignment Expressions (original) (raw)
Tim Peters tim.peters at gmail.com
Mon Apr 23 20:23:49 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 ]
[Tim]
if (diff := x - xbase) and (g := gcd(diff, n)) > 1: return g
[Greg Ewing <greg.ewing at canterbury.ac.nz>]
My problem with this is -- how do you read such code out loud?
In the message in which I first gave that example:
if the diff isn't 0 and gcd(diff, n) > 1, return the gcd.
That's how I thought of it from the start.
In my mind, x - x_base
doesn't even exist except as a low-level
definition of what "diff" means. It's different for the other test:
there g
doesn't exist except as a shorthand for "the gcd". In one
case it's the name that's important to me, and in the other case the
expression. The entire function from which this came is doing all
arithmetic modulo n
, so n
isn't in my mind either - it's a
ubiquitous part of the background in this specific function.
But you did ask how_I_ would read that code ;-) Anyone else is free to read it however they like. I naturally read it in the way that makes most sense to me in its context.
From my Pascal days I'm used to reading ":=" as "becomes". So this says:
"If diff becomes x - base and g becomes gcd(diff, n) is greater than or equal to 1 then return g." But "diff becomes x - base" is not what we're testing!
I don't really follow that. In Python,
if f() and g > 1:
first tests whether f()
"is truthy", regardless of whether it does
or doesn't appear in a binding expression. Because this code is
working with integers, there's an implied "!= 0" comparison.
That makes it sound like the result of x - base may or may not get assigned to diff, which is not what's happening at all.
Then I suggest the problem you're having doesn't stem from the binding expression, but from that you're omitting to fill in the != 0 part: if you're not thrown by "greater than 1", I can't see how you can be thrown by "not zero".
The "as" variant makes more sense when you read it as an English sentence:
if ((x - xbase) as diff) and ... "If x - xbase (and by the way, I'm going to call that diff so I can refer to it later) is not zero ..."
So read the original as "if diff (which is x - x_base) is not zero ...".
Regardless, Guido has already said "as" is DOA (Dead On Arrival) (illustrating that it's also common enough in English to give a short name before its long-winded meaning ;-) ).
- 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 ]