[Python-Dev] PEP 572: Assignment Expressions

Nick Coghlan ncoghlan at gmail.com
Wed Apr 25 01:15:51 EDT 2018


On 25 April 2018 at 13:56, Guido van Rossum <guido at python.org> wrote:
> On Tue, Apr 24, 2018 at 8:24 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>>
>> I also think it would be good for the PEP to spell out the following
>> semantic invariant for code running in a regular namespace:
>>
>>     _rhs = expr
>>     assert (target := _rhs) is _rhs and target is _rhs
>>
>> It's the restriction to single names as targets that makes it possible
>> to impose such a strong assertion about what the syntax means.
>
> Can you elaborate? I don't understand what you mean by this.

The assertion is just spelling out in code form that given the name
binding expression "target := expr", then:

1. the result of the expression itself is "expr", exactly as if the
name binding was omitted
2. that result is also bound to the name "target" in the current scope

The preceding "_rhs = expr" line is included to make the invariant
generalise even to expressions that have side effects or can change
their output based on mutable system state.

Ironically, that may be clearer if I use another assignment statement
to break it out as two separate invariants:

    _rhs = expr
    _inline_result = (bound_name := _rhs)
    assert _inline_result is _rhs
    assert bound_name is _rhs

By contrast, the protocols involved in handling more complex
assignment targets and in handling augmented assignment mean that it
wouldn't be possible to define a similarly simple invariant of what
they mean (since the exact runtime behaviour would be both type and
target dependent).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list