Hacker News new | past | comments | ask | show | jobs | submit login

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.




This 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!




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: