What is the purpose of the "Pyobject" structure and what are the objectives of its members?

Asked

Viewed 85 times

1

I’m analyzing the structure Pyobject of Cpython. The code for this structure follows below.

Structure PyObject:

typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    struct _typeobject *ob_type;
} PyObject;

I have some doubts regarding the members of this structure, more specifically the member _PyObject_HEAD_EXTRA that did not give to understand very well what is his purpose for the structure.

Doubts

  1. What is the structure for PyObject?
  2. What is the purpose of each member of the structure PyObject?

1 answer

2


This structure is an implementation of the python language object system - each instance of any python object is stored in such a structure. There are two. A PyObject that you showed up and the PyVarObject which is for objects with variable size.

We go to the members:

That one _PyObject_HEAD_EXTRA is a macro, follows below her definition:

#define _PyObject_HEAD_EXTRA            \
    struct _object *_ob_next;           \
    struct _object *_ob_prev;

It is used to place pointers to the next object and the previous one, effectively defining a dynamic double-link list that encompasses all objects. This definition is protected by a #ifdef and is only enabled in specific debugging cases: When the developers of CPython are looking for some problem in object allocation, they activate this function to be able to go through the objects in memory and find the problem. But usually it is disabled, and _PyObject_HEAD_EXTRA does nothing.

Continuing, ob_refcnt is the number of references to the object and ob_type is a reference to another object representing the guy of this object. It is usually a class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.