Allow a, b += 1, 1 among other shorthand

We currently can use a, b = 1, 1 through tuple magic. Why not be able to use +=, -=, /=, ect. using this method instead of a, b = a+1, b+1. This should only be possible if the number of elements matched.

1 Like

seems ambiguous, because adding tuples already is used for concatenation:

>>> a, b = 1, 1
>>> (a, b) + (1, 1)
(1, 1, 1, 1)
3 Likes

Currently, x op= y is equivalent to x = x op y with the possibility of op done in place. Limitations on the possible target expressions ‘x’ exclude tuple displays as targets . Note that tuple references are legal targets, with tupx += tupx interpreted as tuple concatenation. Hence t = 2,2; t += 1,; t results in (2, 2, 1). (Other ops are not legal with tuples.)

You are proposing that t op= y, where t is a tuple display containing currently legal augmented assignment targets, be interpreted as t = map(x: x op y, t. For instance, a,b = 2,2; a,b = map(lambda x: x+1, (a,b)); a,b displays (3, 3) in a REPL. This seem too confusing to me also.

13 Likes

Reading code written this way would be highly prone to mistakes, I think. This would be especially true if a and b are not the same type, and thus the = operations on them do not do the same thing.

2 Likes

no.

Sorry, this doesn’t look like it is “human parseable” at all.

-1 from my side.

3 Likes

This should be done using unpacking:

>>> a, b = 1, 1
>>> print(a, b)
1 1
>>> a, b = map(lambda x: x+1, (a, b))
>>> print(a, b)
2 2

You can define an arbitrary translator that uses unpacking too:

>>> a,b,c = 1,1,1
>>> def translate(*args, fn):
...     return map(fn, args)
>>> a,b,c = translate(a,b,c, fn=lambda x: x+1)
>>> print(a,b,c)
2 2 2

Then use functools.partial to create translators:

>>> from functools import partial
>>> add_one = partial(translate, fn=lambda x: x+1)
>>> square = partial(translate, fn=lambda x: x**2)
>>> a,b,c = 3,3,3
>>> a,b,c = square(a,b,c)
>>> print(a,b,c)
9 9 9
>>> a,b,c = add_one(a,b,c)
>>> print(a,b,c)
10 10 10