PyObject vs PyTypeObject
Asked Answered
A

1

6

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.

As answered 30/4, 2020 at 17:26 Comment(2)
There's some great documentation inside the object.h header file: github.com/python/cpython/blob/master/Include/object.hCerebellum
see also the actual documentation: docs.python.org/3/c-api/typeobj.html docs.python.org/3/c-api/object.htmlCerebellum
I
1

TL;DR

  • PyObject is the analogous of object in Python
  • PyTypeObject is the analogous of type 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).

Infraction answered 12/6, 2022 at 19:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.