addressof object with id()

Nobody nobody at nowhere.com
Sun Mar 24 02:54:08 EDT 2013


On Sat, 23 Mar 2013 19:37:35 -0500, Fabian von Romberg wrote:

> I have a single questions regarding id() built-in function.
> 
> example 1:
> 
> var1 = "some string"
> var2 = "some string"
> 
> if use the id() function on both, it returns exactly the same address.

I'm assuming that you used something other than "some string" for your
tests (e.g. something without a space).

Python *may* intern strings. The CPython implementation *does* intern
strings which are valid identifiers (a sequence of letters, digits and
underscores not starting with a digit), in order to optimise attribute
lookups.

FWIW, it also does this for integers between -5 <= n <= 256:

> var1 = 256
> var2 = 255 + 1
> id(var1)
21499520
> id(var2)
21499520
> var3 = var1 + 1
> var4 = 257
> id(var3)
21541752
> id(var4)
21541584

In this case, it just saves on memory.

More generally, an implementation *may* intern any immutable value,
although it's not guaranteed to do so for anything except (IIRC) False,
True and None.




More information about the Python-list mailing list