[Python-Dev] PEP 572: Assignment Expressions

Chris Jerdonek chris.jerdonek at gmail.com
Tue May 1 05:32:39 EDT 2018


On Tue, May 1, 2018 at 2:14 AM, Steve Holden <steve at holdenweb.com> wrote:
> On Tue, May 1, 2018 at 3:36 AM, Chris Jerdonek <chris.jerdonek at gmail.com>
> wrote:
>>
>> 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..
>
> I hope you don't think this recasting, is in any way less confusing to a
> beginner than an inline assignment. This is language abuse!

I didn't make any claims that it wouldn't be confusing (especially as
is). It was just an _idea_. I mentioned it because (1) it uses current
syntax, (2) it doesn't require intermediate assignments or extra
indents in the main body of code, (3) it doesn't even require choosing
intermediate names, and (4) I didn't see it mentioned in any of the
previous discussion. All three of the first points have been major
sources of discussion in the thread. So I thought it might be of
interest.

> In any case, what advantages would it have over simply declaring "stashed"
> as a global inside the function and omitting the confusing subscripting?

Right. Like I said, there are many variations. I just listed one to
convey the general idea.

--Chris


More information about the Python-Dev mailing list