2

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

Gill Bates
  • 14,330
  • 23
  • 70
  • 138

1 Answers1

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