How to get object ID using C API in Python?

Viewed 192

I wonder - is there a canonical way of getting object's ID using CPython's C API?

1 Answers

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.

Related