How to extend a tuple of tuples?

Antoon Pardon antoon.pardon at rece.vub.ac.be
Tue Sep 13 06:01:20 EDT 2016


Op 13-09-16 om 11:27 schreef Chris Angelico:
> On Tue, Sep 13, 2016 at 5:25 PM, Antoon Pardon
> <antoon.pardon at rece.vub.ac.be> wrote:
>> Op 12-09-16 om 23:29 schreef Chris Angelico:
>>> On Tue, Sep 13, 2016 at 7:19 AM, BartC <bc at freeuk.com> wrote:
>>>> By the same argument, then strings and ints are also mutable.
>>>>
>>>> Here, the original tuple that a refers to has been /replaced/ by a new one.
>>>> The original is unchanged. (Unless, by some optimisation that recognises
>>>> that there are no other references to it, the original is actually appended
>>>> to. But in general, new objects are constructed when implementing +=.)
>>> And by definition, that optimization cannot be detected. At best, all
>>> you could do is something like:
>>>
>>> old_id = id(a)
>>> a += something
>>> if id(a) == old_id:
>>>     print("We may have an optimization, folks!")
>>>
>>> But that can have false positives. If two objects do not concurrently
>>> exist, they're allowed to have the same ID number.
>> 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.

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])




More information about the Python-list mailing list