[Python-Dev] PEP 572: Assignment Expressions

Chris Angelico rosuav at gmail.com
Tue Apr 17 15:44:56 EDT 2018


On Wed, Apr 18, 2018 at 5:28 AM, Tim Peters <tim.peters at gmail.com> wrote:
> I'll channel that Guido would be happiest if this rule were followed:
>
> Given an assignment statement using "=", the meaning is the same if
> "=" is replaced with ":=".

That's broadly the intention. At the moment, there are two exceptions:

1) Augmented assignment isn't a thing
2) Chained assignment isn't a thing, which means that the assignments
operate right-to-left
2a) Assignment

> In particular, the expression at the far right is evaluated once, and
> - in case of chained assignments - is applied in turn to each target
> left-to-right.

I'll toy with this and see if I can implement it sanely. If so,
that'll eliminate one more distinction.

> Otherwise the semantics of "=" and ":=" can be very different indeed.

TBH, the common cases won't actually be much affected. You give this example:

k := container[k] := value

but that's not going to be more common. What I'm more likely to see is
something like this:

k, container[k] = new_key(), new_value()

which can instead be written:

container[k := new_key()] = new_value()

and is, IMO, clearer that way.

> So, then, e.g., and assuming the rule above always applies:
>
> [Nick]
>> Tuple unpacking:
>>
>>     What's the result type for "a, b, c := range(3)"? Is it a range()
>> object? Or is it a 3-tuple? If it's a 3-tuple, is that 3-tuple "(1, 2,
>> 3)" or "(a, b, range(3))"?
>
> It's the range object range(3).  Same as in:
>
>     x = a, b, c = range(3)
>
> `x` is bound to the range object range(3).

At the moment, "x = a, b, c := range(3)" will set c to range(3), then
build a tuple of that with the existing values of a and b. You can,
however, parenthesize the (a, b, c) part, and then it'll behave as you
say.

>> Whichever answers we chose would be surprising at least some of the
>> time, so it seems simplest to disallow such ambiguous constructs, such
>> that the only possible interpretation is as "(a, b, range(3))"
>
> That's why Guido would be happiest with the rule at the top.  "The
> answers" can already be surprising at times with current assignment
> statements, but they are well defined.  It would be mondo bonkers to
> make up entirely different subtle answers ;-)

Wholeheartedly agreed.

ChrisA


More information about the Python-Dev mailing list