osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why is augmented assignment of a tuple with iterable unpacking invalid syntax?


Eugene Alterman <eugalt at gmail.com> writes:

> a = 1, 2, 3
>
> b = *a,           # assignment - OK
> b += *a,          # augmented assignment - syntax error
>
> Need to enclose in parenthesis:
>
> b += (*a,)
>
> Why isn't it allowed with an augmented assignment, while it is OK with a
> regular assignment?
>

Syntactically (i.e. according to the grammar):
The right-hand side of an assignment has as one of the alternative a starred_expression, which includes starred and unstarred expressions.

The right-hand side of an augmented assignment has an expression_list there. (The other option is both cases is a yield_expression.) And if it is a list (i.e. there is a comma in it), it is a tuple.

Semantically:
x += y is more or less equivalent to x = x + y, except that x is only evaluated once, and y is treated as a unity (think implicit parentheses around it). So the y is basically part of an expression. But starred expressions are not allowed in expressions, except within explicit parentheses.
-- 
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]