2 ms·
I once broke some Python by changing a = a + b to a += b. If a and b are lists, the latter modifies the existing list (which may be referenced elsewhere) inste
by skobes 1y ago
I once broke some Python by changing a = a + b to a += b.
If a and b are lists, the latter modifies the existing list (which may be referenced elsewhere) instead of creating a new one.
I think Python is the only language I've encountered that uses the + operator with mutable reference semantics like this. It seems like a poor design choice.
- pansa2 1y agoThis is one of the absolute worst design mistakes in Python. The example you give (that `a = a + b` and `a += b` aren't equivalent) is bad enough: >>> a = b = [1, 2, 3] >>> a = b = [1, 2, 3] >>> a = a + [4] >>> a += [4] >>> a, b >>> a, b ([1, 2, 3, 4], [1, 2, 3]) ([1, 2, 3, 4], [1, 2, 3, 4]) What's worse is that sometimes, they are equivalent: >>> a = b = (1, 2, 3) >>> a = b = (1, 2, 3) >>> a = a + (4,) >>> a += (4,) >>> a, b >>> a, b ((1, 2, 3, 4), (1, 2, 3)) ((1, 2, 3, 4), (1, 2, 3)) And even worse, in order to support a version of `a += b` that sometimes modifies `a` (e.g. with lists), and sometimes doesn't (with tuples), the implementation of the `+=` operator is convoluted, which can lead to: >>> t = ([1, 2, 3], ['a']) >>> t[0] += [4] TypeError: 'tuple' object does not support item assignment >>> t ([1, 2, 3, 4], ['a']) The operation raises a TypeError, despite having succeeded!