Tuples and immutability

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Mar 8 03:17:31 CET 2014

Duncan Booth wrote:
> Is there any reason why tuples need to throw an exception on assigning to 
> the element if the old value and new value are the same object?

It would make introspection misleading, because tuples
would have a __setitem__ method event though they don't
actually support item assignment.

Also, it would solve the problem for tuples in particular,
but not for any other immutable type -- they would all
have to implement the same behaviour independently to
enjoy the benefit.

Here's another idea: If the __iadd__ method returns the
same object, *and* the LHS doesn't have a __setitem__
method, then do nothing instead of raising an exception.

Peter Otten wrote:

 > Traceback (most recent call last):
 >   File "<stdin>", line 2, in <module>
 >   File "<stdin>", line 4, in __setitem__
 > TypeError: 257 is not 257
 > I'm not sure "help" is the right word here ;)

I don't think that's a problem, because the use case
being addressed is where the object performs in-place
modification and always returns itself. Any object that
doesn't return itself is not modifying in-place, even
if the returned object happens to be equal to the
original one.


More information about the Python-list mailing list