[Python-Dev] PEP 572: intended scope of assignment expression

Chris Angelico rosuav at gmail.com
Thu Jul 5 09:18:12 EDT 2018


On Thu, Jul 5, 2018 at 11:14 PM, Gustavo Carneiro <gjcarneiro at gmail.com> wrote:
> On Thu, 5 Jul 2018 at 13:43, Victor Stinner <vstinner at redhat.com> wrote:
>>
>> Hi,
>>
>> My work (*) in the "Assignment expression and coding style: the while
>> True case" thread helped me to understand something about the
>> *intended* scope.
>>
>> While technically, assignment expressions keep the same scoping rules
>> than assignment statements, writing "if (x := func()): ..." or "while
>> (x := func()): ..." shows the "intented" scope of the variable. Even
>> if, as explained properly in the PEP, the scope is wider (for good
>> reasons) as "for line in file: ..." keeps line alive after the loop
>> (nothing new under the sun). It's something subtle that I missed at
>> the first read (of the code and the PEP), the difference is not
>> obvious.
>>
>> x = func()
>> if x:
>>     ... # obviously use x
>> # do we still plan to use x here?
>> # it's non obvious just by reading the if
>>
>> versus
>>
>> if (x := func()):
>>     ... # obviously use x
>> # ":=" in the if "announces" that usually x is no longer used
>> # here, even if technically x is still defined
>
>
> I don't know if you're trying to propose something clever here, like "if (x
> := func()):" would assign to 'x' only inside the "then" body of the if, but
> IMHO that would be a terrible idea:
>
> 1. it makes AE harder to explain.  Right now you can simply say AE works
> just like any regular assignment, except that you can use in an expression.
> If you start adding exceptions to the rule, things get harder and harder to
> explain;
> 2. it would probably have a cost in terms of performance: you'd have to
> create another scope for every "then" body of any if statement that contains
> an AE.  And, again, more scopes = things harder to understand.
>

The time machine strikes again. There were actually semantics defined
in PEP 572 that would have done exactly this. They were sane,
coherent, and internally consistent, but ultimately, not as useful as
just maintaining the equivalence of "x = 2" and "x := 2". Subscope
semantics aren't as impossible as you're implying here.

ChrisA


More information about the Python-Dev mailing list