[Python-ideas] Inline assignments using "given" clauses

Chris Angelico rosuav at gmail.com
Sun May 13 13:21:18 EDT 2018

On Mon, May 14, 2018 at 12:20 AM, Juancarlo Añez <apalala at gmail.com> wrote:
>> That's an excellent point. What's "special_gcd" and how does it differ
>> from normal gcd? How am I supposed to grok that just from reading the
>> code above?
>> Do I have to dig into the source of special_gcd to understand it?
> One would usually define functions like special_gcd() inline, right before
> it is first used.

Okay, then. What happens to the succinctness?

On Sun, May 13, 2018 at 10:27 AM, Juancarlo Añez <apalala at gmail.com> wrote:
>>     if (diff := x - x_base) and (g := gcd(diff, n)) > 1:
>>          return g
> I don't see the advantage in that succinctness:
> g = special_gcd(x - x_base, n)
> if g:
>     return g

It's actually this:

def special_gcd(diff, n):
    return diff and gcd(diff, n)
g = special_gcd(x - x_base, n)
if g:
    return g

Yes, very succinct. You can't have it both ways; either you need a
name that completely defines the function, such that it can be placed
out-of-line without needing to be read; or you're just creating an
inline helper function, which doesn't shorten your code at all, and
just adds another layer of wrapping around everything.

Remember, you're contrasting with one of two options: either a nested
if, or an inline 'and' with the ability to capture values. What you've
created here is a multi-line way of capturing a value. That's all.


More information about the Python-ideas mailing list