How to extend a tuple of tuples?

Chris Angelico rosuav at gmail.com
Tue Sep 13 06:09:33 EDT 2016


On Tue, Sep 13, 2016 at 8:01 PM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
>>> You could do the following:
>>>
>>> old_a = a
>>> a += something
>>> if old_a is a:
>>>     print("We have an optimization, folks!")
>>>
>> Uhm... that defeats the whole point of it being an optimization. See
>> above, "there are no other references to it". :)
>
> What do you mean? If it is an optimization, then the object a refers to
> will be mutated, whether or not there are other references. These other
> reference will all still refer to the same object that is now mutated.

The language spec says that tuples are immutable. If there's an
optimization, it is pretending that the tuple is immutable if and only
if there are no other references to that object. But old_a is another
reference to that object!

> So how does my example defeats the point of it being an optimization?
>
>> If this condition is ever true, Python's language spec has been violated.
>>
> Then python seems to be broken:
>
> ]]] a = range(3)
> ]]] old_a = a
> ]]] a += [8, 13]
> ]]] id(a), id(old_a)
> (140062018784792, 140062018784792)
> ]]] a, old_a
> ([0, 1, 2, 8, 13], [0, 1, 2, 8, 13])

A range object is not a tuple. Nor (since you were probably running
this in Python 2) is a list.

ChrisA



More information about the Python-list mailing list