Comment by pansa2
3 years ago
`a += b` sometimes does the same thing as `a = a + b`:
>>> a = b = (1, 2) >>> a = b = (1, 2)
>>> a += (3,) >>> a = a + (3,)
>>> print(a, b) >>> print(a, b)
(1, 2, 3) (1, 2) (1, 2, 3) (1, 2)
Sometimes it does something different:
>>> a = b = [1, 2] >>> a = b = [1, 2]
>>> a += [3] >>> a = a + [3]
>>> print(a, b) >>> print(a, b)
[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2]
IMO if that behaviour had been "carefully thought out" by the language designers, it should have been obvious that it's a bad idea.
Failing that, the implementation of that behaviour is convoluted - so the designers should have paid attention to the Zen of Python: "If the implementation is hard to explain, it's a bad idea".
Failing that, if the behaviour had been "explored to great lengths", the designers would have understood how it interacts with other language features - in particular, nested mutable and immutable objects.
Python's designers failed to do any of these things, so we've ended up with an operator with unpredictable behaviour and a long FAQ entry [0] about how its possible for an operator to both succeed and fail at the same time:
>>> a = ([1, 2], 4)
>>> a[0] += [3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
([1, 2, 3], 4)
[0] https://docs.python.org/3/faq/programming.html#why-does-a-tu...
No comments yet
Contribute on Hacker News ↗