Why not a, b += i, j? (augmented assignment via tuple unpacking)

Jeff Epler jepler at unpythonic.net
Tue Nov 26 16:29:16 EST 2002


On Tue, Nov 26, 2002 at 09:01:29PM +0000, Grant Edwards wrote:
> In article <KbRE9.534$RQ3.26615908 at newssvr17.news.prodigy.com>, Steven Rumbalski wrote:
> 
> > In python I can write:
> > 
> > a, b = i, j
> > 
> > but the following is not legal:
> > 
> > a, b += i, j
> > 
> > Is there a reason that allowing this would be bad?
> 
> If it were allowed, what do you propose it would do?
> 
> > Why does Python forbid this?
> 
> First tell us what you think it would do were it legal.  :)

First, define
    def iadd(a, b):
        a += b
        return a

Since 
    a += i
is equivalent to
    a = iadd(a, i)
then
    a, b += i, j
is obviously equivalent to
    a, b = iadd((a, b), (i, j))
Therefore, the meaning of
    a, b += i, j
is the same as
    raise ValueError, "unpack tuple of wrong size"
except that an extra intermediate value is computed.

I suspect that the OP actually wants it to be equivalent to
    a, b = iadd(a, i), iadd(b, j)
but in that case, what is
    a, b += t
equivalent to?  Maybe
    a, b = map(iadd, (a, b), t)
?
    __t = tuple(t)
    if len(__t) != 2: raise ValueError, "unpack object of wrong size"
    try:
        a, b = iadd(a, __t[0]), iadd(a, __t[1])
    finally:
        del __t

What about
    t += a, b
? The latter already has a meaning, for instance if t is an instance of
    class T(list):
        def __add__(self, other):
            other = list(other)
            list.__add__(self, other)
        def __iadd__(self, other):
            other = list(other)
            return list.__iadd__(self, other)

    >>> t = T()
    >>> t
    []
    >>> t += 1,2
    >>> t
    [1, 2]
This fact implies the behavior I first (sarcastically) suggested ("the
left and right sides of the augmented assignment operators are the first
and second arguments to a single iadd() invocation")

Jeff




More information about the Python-list mailing list