[Python-Dev] PEP 572: Assignment Expressions

Chris Jerdonek chris.jerdonek at gmail.com
Mon Apr 30 22:36:43 EDT 2018


On Thu, Apr 26, 2018 at 10:33 AM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 25.04.2018 01:19, Steven D'Aprano wrote:
>>
>> Sorry, gcd(diff, n) is not the "perfect name", and I will tell you that
>> sometimes g is better. [...]
>
> We were talking about the real-world code snippet of Tim (as a justification
> of := ) and alternative rewritings of it without resorting to new syntax.

Apologies if this idea has already been discussed (I might have missed
the relevant email), but thinking back to Tim's earlier example--

    if (diff := x - x_base) and (g := gcd(diff, n)) > 1:
        return g

it occurs to me this could be implemented with current syntax using a
pattern like the following:

    stashed = [None]

    def stash(x):
        stashed[0] = x
        return x

    if stash(x - x_base) and stash(gcd(stashed[0], n)) > 1:
        return stashed[0]

There are many variations to this idea, obviously. For example, one
could allow passing a "name" to stash(), or combine stash / stashed
into a single, callable object that allows setting and reading from
its store. I wonder if one of them could be made into a worthwhile
pattern or API..

--Chris


More information about the Python-Dev mailing list