Tuples and immutability

Mark H. Harris harrismh777 at gmail.com
Sun Mar 2 03:15:10 CET 2014


On Saturday, March 1, 2014 3:21:44 PM UTC-6, Mark H. Harris wrote:
> On Friday, February 28, 2014 11:16:18 PM UTC-6, Ian wrote:

hi Ian,  I thought of something else after I slept on it, so to speak. 

Consider this: 

>>> s=(2,3,[42,43,44],7) 
>>> s[2] 
[42, 43, 44] 
>>> 

s[2] is a list. We should be able to change s[2] even though its within a tuple, 
like this: 

[42, 43, 44] 
>>> s[2].append(45) 
>>> s[2] 
[42, 43, 44, 45]       <===== no error 
>>> 

or like this: 

>>> s[2] 
[42, 43, 44, 45] 
>>> s[2]=s[2]+[46] 
Traceback (most recent call last): 
  File "<pyshell#8>", line 1, in <module> 
    s[2]=s[2]+[46]                    <==========error,  but look below====== 
TypeError: 'tuple' object does not support item assignment 
>>> 
>>> s[2] 
[42, 43, 44, 45]        <=========also no change to list  !! 
>>> 

The point I'm trying to make with this post is that  s[2]+=[46]  
and  s[2]=s[2]+[46]  are handled inconsistently.  In each case 
(whether the list is part of a tuple or not)  s[2]  is a valid 
list and should be mutable.   In every case, in fact, it is.  
In each case, in fact, the change might occur.  But, the change 
occurs in the first case (append) without an error.  The change 
occurs in the next case too (+=) but with an error not related 
to the tuple.  The change does not occur in the third case
(s=s+ with an error) but the list is not changed ! 

We all know this is not good. We also all know that its because 
of implementation details the user/coder should not need to know.  

QED:  a bug. 

Having slept on it, I am remembering my Zen of Python:  Errors 
should never pass silently, unless explicitly silenced.  It looks 
to me like  (+=)  in this case is not being handled correctly 
under the covers.  At any rate the three scenarios of trying to 
change a mutable list as an immutable tuple item should be handled 
consistently.  
Either we can change the tuple item (if its a list) or we can't.  
Also, if we cannot then the expected error should 
be consistent. 

Cheers 


Hi ,  I'm experimenting a bit with TextWrangler and gg to see if I can 
at least solve my double spacing and wrap problems with cut
a paste for the moment.

Looks ok?

Thanks



More information about the Python-list mailing list