Tuples and immutability

Ian Kelly ian.g.kelly at gmail.com
Sat Mar 1 06:16:18 CET 2014

On Fri, Feb 28, 2014 at 5:22 PM, Mark H. Harris <harrismh777 at gmail.com> wrote:
> I really think this is a bug; honestly.  IMHO it should be an error to use  +=  with an immutable type and that means not at all.  In other words,  the list should not even be considered, because we're talking about changing a tuple... which should not be changed (nor should its members be changed).

How would you propose doing that?  Bear in mind that while Python
knows that tuples specifically are immutable, it doesn't generally
know whether a type is immutable.  The best it can do is try the
operation and raise a TypeError if it fails.  So you can special-case
the code for += to fail earlier if the left side of the assignment is
an tuple index, but it's not currently possible to do the same for
arbitrary immutable user types.

Even if that is solved, how you do propose preventing the simple workaround:
    tup = (0, [1, 2, 3], 4)
    thelist = tup[1]
    thelist += [5, 6]
which currently works just fine.

I don't think that entirely disallowing mutable objects inside tuples
is an acceptable solution.  For one, it would mean never allowing
instances of custom classes.  They could then basically only contain
strings, numbers, frozensets, and other tuples.  For another, my
experience suggests that if I'm putting a list inside a tuple in the
first place, I am generally not relying on the immutability of that
tuple anyway, so I don't really see this as fixing an actual problem.
The usual reason for wanting an immutable object is to hash it, and a
tuple containing a list already can't be hashed.

More information about the Python-list mailing list