Reputation: 110592
How is the id
of an object computed? https://docs.python.org/3/library/functions.html#id
It seems there is a place in a class to do equality, with __eq__
but where is the is
operation done, and how is the id
arrived at?
Upvotes: 0
Views: 80
Reputation: 369633
How is the
id
of an object computed? https://docs.python.org/3/library/functions.html#id
You don't know. This is what the documentation has to say:
id
(object)Return the “identity” of an object. This is an 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.
That is all the guarantees that Python makes about id()
:
int
id()
at the same timeid()
sAnd that is all the guarantees that Python makes. In particular, the documentation explicitly points out one guarantee that it doesn't make:
id()
s are not globally unique in space and time, i.e. two different objects may have the same id()
at different timesYou will also notice that the documentation makes no guarantees about how the id()
is computed.
It does, however, say this:
CPython implementation detail: This is the address of the object in memory.
This actually re-inforces the fact there are no guarantees about how id()
s are computed by explicitly stating that this
In fact, it is actually impossible for any implementation other than CPython to implement id()
this way, since all other implementations have either moving garbage collectors (PyPy, PythonOMR), or don't even have a concept of "memory address" at all (Jython, IronPython, GraalPython).
It seems there is a place in a class to do equality, with
__eq__
but where is theis
operation done, and how is theid
arrived at?
Let me break that down into two answers:
where is the
is
operation done
It is defined as part of the Python Language Specification, just like, say def
. It does not translate into a method call, there is no way to modify its behavior.
how is the
id
arrived at
You don't know, can't know, and mustn't know. All you know is that it is an identifier, the actual value is opaque.
Upvotes: 1
Reputation: 64398
You can think of id(obj)
as some sort of address of the object.
The way it is computed, and what the value represents, is implementation-dependent, and you should not make any assumptions about the value.
What you need to know:
id
will not change as long as the object existsid
sid
as another object which has already been deallocated (since it is gone, its address may be reused).a is b
is equivalent to id(a) == id(b)
.You cannot override the way id
is computed, nor the way is
behaves, like you'd override operators such as __eq__
.
Upvotes: 2
Reputation: 23546
From the page you have provided URL for: "CPython implementation detail: This is the address of the object in memory." -- so id
is basically an address, not more not less.
Upvotes: 1