[Python-ideas] On evaluating features [was: Unpacking iterables for augmented assignment]

MRAB python at mrabarnett.plus.com
Tue Aug 28 15:46:23 EDT 2018


On 2018-08-28 18:57, Guido van Rossum wrote:
> So we currently have iterable unpacking:
> 
>    a, b, c = x  # x better be an iterable of exactly 3 values
> 
> as well as tuple packing:
> 
>    x = a, b, c  # sets x to a tuple of 3 values (a, b, c)
> 
> and we can combine these, e.g.:
> 
>    a, b, c = x, y, z
> 
> and this still creates an intermediate, anonymous tuple from the values 
> on the right. (At least in the formal semantics -- it may be optimized 
> away if that can be done safely.)
> 
> This leads to the following idioms:
> 
>    a, b = b, a  # swap variables
>    a, b, c = b, c, a  # rotate variables
> 
> That's all well established (and I have to admit that the elegance of 
> the swap idiom was one reason to add this to the earliest version of the 
> language).
> 
> The proposal on the table is to see if there's a logical extension for 
> augmented assignment.
> 
> If we look at this:
> 
>    a, b, c = x, y, z
> 
> and notice that it's equivalent to this:
> 
>    a = x
>    b = y
>    c = z
> 
> we might propose (as the OP did) that this:
> 
>    a, b, c += x, y, z
> 
> could be made equivalent to this:
> 
>    a += x
>    b += y
>    c += z
> 
> but the question is, what would this do?
> 
>    a, b, c += x
> 
> Presumably it requires that x is an iterable of 3 values, so it would be 
> translated to this first:
> 
>    x0, x1, x2 = x
>    a, b, c += x0, x1, x2
> 
> However, a user who doesn't typically think about the actual semantics 
> of iterable unpacking and tuple packing might think this would instead 
> mean the following:
> 
>    a += x
>    b += x
>    c += x
> 
> IOW they might think that this is a clever way to increment three 
> variables at once:
> 
>    a, b, c += 1
> 
> This ambiguity (in naive users' minds) leads me to frown upon the proposal.
> 
By the same logic, wouldn't such a naive user also expect:

     a, b, c = 0

to set three variables to 0?

> If we were to ignore the naive view, we could definitely give semantics 
> to `a, b, c += ...` -- basically it would unpack the RHS into the right 
> number of elements (if needed) and call __iadd__ pairwise. But I am not 
> so keen, because the ambiguity of `a, b, c += x`.
> 
> Perhaps someone can do some research and unearth real code that contains 
> series of += assignments that would become more readable by collapsing 
> them into a single line using the proposed construct.
> 


More information about the Python-ideas mailing list