I wonder - is there a canonical way of getting object's ID using CPython's C API?
Asked
Active
Viewed 258 times
1 Answers
3
Object id is just the pointer value:
PyObject *some_py_object = ...;
intptr_t id = (intptr_t)some_py_object;
Or if you want it as a Python object:
PyLong_FromVoidPtr(some_py_object)
This is a CPython specific implementation detail. If you're concerned about compatibility with other versions of Python (e.g. PyPy through their C API compatibility layer) you should probably import builtins
, get the attribute id
and call it, using the normal C-API mechanisms for doing that.

DavidW
- 29,336
- 6
- 55
- 86
-
intptr_t id = (intptr_t) some_py_object; // cast is needed – Kir Chou Mar 31 '22 at 13:06