Mutable objects inside tuples - good or bad?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Apr 7 22:53:35 EDT 2014


On Mon, 07 Apr 2014 20:16:05 -0400, Terry Reedy wrote:

> On 4/7/2014 11:26 AM, Paul Kölle wrote:
> 
>>  >>> c = (1,2,3)
>>  >>> d = (1,2,3)
>>  >>> c is d
>> False
> 
> An implementation would be allowed to make that True, as it does for
> small ints and short strings that could be identifiers.

And indeed, that happens in at least one circumstance in Python 3.3:

py> a, b = [(1, 2, 3) for _ in range(2)]
py> a is b
True

But:

py> x = 3
py> a, b = [(1, 2, x) for _ in range(2)]
py> a is b
False


As Terry knows, but for the benefit of others who may not, the re-use of 
objects leading to object identity ("a is b") is an implementation detail 
which *cannot be relied on*. It can change without notice, and is not a 
promise of the language.


>  >>> a = 'one'
>  >>> b = 'one'
>  >>> a == b; a is b
> True
> True

In this case, it is a promise of the language that a will equal b: a and 
b must be bound to strings with the same value. But an implementation 
detail whether Python creates two strings, both with value "one", or just 
a single string, and uses it for both a and b.



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list