Address of an immutable object

Alf P. Steinbach alfps at start.no
Sun May 30 13:44:09 EDT 2010


* candide, on 30.05.2010 19:38:
> Suppose a Python program defines an integer object with value 42. The
> object has an "address" we can capture with the built-in function id() :
>
>  >>> a=42
>  >>> id(a)
> 152263540
>  >>>
>
> Now I was wondering if any integer object with value 42 will be refered
> at the same adress with the above id.
>
> Some experiments tend to show that it may be the case, for instance :
>
>  >>> a=42
>  >>> id(a)
> 152263540
>  >>> id(42)
> 152263540
>  >>> b=2*21
>  >>> id(b)
> 152263540
>  >>> c=0b101010
>  >>> id(c)
> 152263540
>  >>> d={"foo":42, "bar":"foo"}
>  >>> id(d["foo"])
> 152263540
>  >>> L=["foo",(51,([14,42],5)),"bar"]
>  >>> id(L[1][1][0][1])
> 152263540
>  >>> del a
>  >>> id(L[1][1][0][1])
> 152263540
>  >>> zzz=range(1000)
>  >>> id(zzz[42])
> 152263540
>  >>>
>
> Even you can't make a deep copy :
>
>
>  >>> from copy import deepcopy
>  >>> a=42
>  >>> from copy import deepcopy
>  >>> z=deepcopy(a)
>  >>> id(a), id(z)
> (152263540, 152263540)
>  >>>
>
> So is the following true :
>
> Two non mutable objects with the same value shall be allocated at a
> constant and unique address ?

No.

First, id() doesn't generally provide an address. It does that in CPython, but 
more generally it just provides a unique integer identifying the reference. You 
can think of it as the "reference value" if you want; it's what's copied by an 
assignment to a variable.

Second, the reason that you get the same id for various 42 objects is that 
CPython uses a cache of "small integer" objects. As I recall the cache ranges 
from -5 to some 127 or so (or perhaps it was double that). Any value outside 
that cached range you'll see different id's for the same value.


Cheers & hth.,

- Alf

-- 
blog at <url: http://alfps.wordpress.com>



More information about the Python-list mailing list