[Python-ideas] Inline assignments using "given" clauses
Tim Peters
tim.peters at gmail.com
Sat May 12 20:12:41 EDT 2018
[attributions lost - sorry, but I can't get 'em back]
...
>>> Similar to import statements, optional parentheses could be included in
>>> the
>>> grammar, allowing the name bindings to be split across multiple lines:
>>>
>>> if diff and g > 1 given (
>>> diff = x - x_base,
>>> g = gcd(diff, n),
>>> ):
>>> return g
>> I'm well behind, but... this! This turns "given" into a +0.8 for me.
>>
>> That's really nice. It reads clearly too.
>>
> That's longer than this:
>
> diff = x - x_base
> g = gcd(diff, n)
> if diff and g > 1:
> return g
>
> which is already valid.
Since that was my example to begin with, I think it's fair to point
out that they all miss a key part of the original example: this code
is working with multi-thousand bit integers, and calling gcd() is
expensive. It was a key point that
if (diff := x - x_base) and (g := gcd(diff, n)) > 1:
return g
didn't call gcd() _at all_ unless `diff` was non-zero. The original
real-life code was:
diff = x - x_base
if diff:
g = gcd(diff, n)
if g > 1:
return g
More information about the Python-ideas
mailing list