Python under the hood — id()
The python builtin function id() is used to get the identity of an object during the object’s lifetime, the documentation of id has a small one-liner on how id is implemented
CPython implementation detail: This is the address of the object in memory.
For the uninitiated CPython is the implementation of Python written in C and that is the default Python we get when we spin up a Python interpreter. Let’s dissect id() and understand what the above statement means.
Get Derrick Joseph’s stories in your inbox
Join Medium for free to get updates from this writer.
All python builtin functions reside in the file CPython/Python/builtinmodule.c, the functions defined in builtins.c follows the naming convention of the function name preceded by “buitin_”, therefore id() would be “builtin_id”, here is the code.
Line 1195 forwards the reference of the object passed as the argument to id() over to another function PyLong_FromVoidPtr residing in CPython/Objects/longobject.c
The magic happens at line 1036 the Python documentation explains PyLong_FromUnsignedLong as
Return a new
PyLongObjectobject from a Cunsigned long
basically PyLong_FromUnsignedLong creates a Python object of whatever value is passed as the argument, so what is the argument passed getting passed ?
The function PyLong_FromVoidPtr takes only a single argument which is a generic pointer(void *), i.e. reference to the object which was passed to id(), the reference is type-casted as an unsigned long long and packaged as a Python object and returned, a simple C implementation of the same is as follows.
So simply put, the builtin id(), type casts a generic pointer, referencing the object to an unsigned long long and packages the value as a Python object and presents to us as the identity of the object.
Surprisingly this is a very simple trick, back in school I always used to get tripped whenever I made the mistake of typecasting generic pointers !






