Tuples and immutability
Duncan Booth
duncan.booth at invalid.invalid
Fri Mar 7 04:33:49 EST 2014
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"
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list