Alex V
Alex V

Reputation: 1

What exactly is id() displaying?

The id() function appears to identify the value, not the object. Which of the entities below is actually an object: x ? 11 ? 12 ?

id(object) Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

$ python
Python 2.7.5 (default, May  3 2017, 07:55:04)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> id(11)
11311992
>>> x=11
>>> id(x)
11311992
>>> id(12)
11311968
>>> x=12
>>> id(x)
11311968

Upvotes: 0

Views: 71

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126777

id does indeed uniquely identify live objects (as in: if id(a) == id(b), then a is b == True, and if id(a) != id(b), a is b == False). The behavior you see (unrelated "instances" of 11 being actually the same object) comes from an implementation detail of CPython.

In CPython the literal 11 will always return the same object, as there's an interned cache for numbers from -5 to 256. Try your code with 257, and you'll see you'll get different ids every time - unless you write them in the same expression, as in that case there's an optimization that will provide you the same object.

Still, this shows that investigating the identity of immutable objects is pretty much pointless - two immutable objects with the same value may or may not actually be the same object, depending on caches/optimizations, and you just shouldn't care in your code. For immutable objects, all you should care about is their value.

Upvotes: 1

ash
ash

Reputation: 5529

id() returns the ID of objects, but it sounds like you're using the word "value" to describe what Python refers to as an object. In Python, "object" has a special meaning – everything is an object. (In other words, for any x, isinstance(x, object) is true.)

e.g. 11 and 12 are both objects:

>>> isinstance(11, object)
True

For more details, you may want to see this answer (or it may just be confusing – it certainly confuses me!)

Upvotes: 0

Related Questions