I am trying to build a Python-C interface, but when I looked at the source code, I am confused by PyObject
and PyTypeObject
. Can someone please explain the difference between them? It would be nice if someone could provide an example.
TL;DR
PyObject
is the analogous ofobject
in PythonPyTypeObject
is the analogous oftype
in python
Let's check the docs for PyTypeObject
:
The C structure of the objects used to describe built-in types.
This is the analogous to the classes as instances of type
in python. This contains information about the type itself (e.g., the type name, docstring, the constructor function, etc.)
Now let's check the docs for PyObject
:
All object types are extensions of this type....
This means you can reference any object as a PyObject*
pointer. For example:
PyObject *some_number = PyLong_FromLong(42);
... In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object.
As the bold part says, all PyObject
's contains a pointer to the type of that object which is a PyTypeObject
.
In the example above, some_number
is specifically a PyLongObject
(which represents a Python integer object), and the structure that represents the integer type itself is PyLong_Type
(which what you get from some_number->ob_type
).
© 2022 - 2025 — McMap. All rights reserved.