Tuples and immutability

Alister alister.ware at ntlworld.com
Fri Mar 7 06:51:28 EST 2014


On Fri, 07 Mar 2014 09:33:49 +0000, Duncan Booth wrote:

> Chris Angelico <rosuav at gmail.com> wrote:
> 
>> On Sat, Mar 1, 2014 at 1:41 AM, Joshua Landau <joshua at landau.ws> wrote:
>>> Would it be better to add a check here, such that if this gets raised
>>> to the top-level it includes a warning ("Addition was inplace;
>>> variable probably mutated despite assignment failure")?
>> 
>> That'd require figuring out whether or not the variable was actually
>> mutated, and that's pretty hard to work out. So there's a FAQ entry,
>> which Zachary already posted:
>> 
>> http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-r
>> aise-an-exception-when-the-addition-works
>> 
>> Also, we just answer this question every now and then :) Presumably
>> more often on -tutor than here.
>> 
>> ChrisA
> Another take on this that I haven't seen discussed in this thread:
> 
> 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?
> 
> If I say:
> 
>     a = ("spam", [10, 30], "eggs")
> 
> then
> 
>     a[0] = a[0]
> 
> won't actually mutate the object. So tuples could let that silently
> pass.
> Then you would be able to safely do:
> 
>     a[1] += [50]
> 
> but this would still throw an exception:
> 
>     a[0] += "x"

I would think it would be better if the exception was thrown before the 
assignment to the list took place
simply seeing that a modification action was being applied to a tupple 
should be enough.
this would alert the programmer to the fact that he was trying something 
that may have undesired consequences
 



-- 
Old age is the harbor of all ills.
		-- Bion



More information about the Python-list mailing list