Address of an immutable object

Simon Brunning simon at brunningonline.net
Sun May 30 14:36:21 EDT 2010


On 30 May 2010 18:38:23 UTC+1, candide <candide at free.invalid> wrote:
> Two non mutable objects with the same value shall be allocated at a constant and unique address ?

Nope.

>>> a = 999
>>> b = 999
>>> id(a) == id(b)
False

Your statement will be the case for small integers, but this in an
implementation detail. Indeed, this used to be the case for integers
up to 100 (IIRC) or thereabouts, but it's now the case up to 256:

>>> a = 256
>>> b = 256
>>> id(a) == id(b)
True
>>> a = 257
>>> a = 257
>>> id(a) == id(b)
False

Some identifier-like strings are also interned like this:

>>> a = 'foo'
>>> b = 'foo'
>>> id(a) == id(b)
True
>>> a = 'two words'
>>> b = 'two words'
>>> id(a) == id(b)
False

But again, it's an implementation detail, and shouldn't be relied upon.

This same issue also comes up with people noticing that they can
compare small integers with the 'is' operator, and getting a surprise
when bigger numbers come along:

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False

-- 
Cheers,
Simon B.



More information about the Python-list mailing list