Підтримка циклічного збирання сміття

Підтримка Python для виявлення та збирання сміття, яке включає циклічні посилання, вимагає підтримки типів об’єктів, які є «контейнерами» для інших об’єктів, які також можуть бути контейнерами. Типи, які не зберігають посилання на інші об’єкти, або які зберігають лише посилання на атомарні типи (такі як числа або рядки), не потребують явної підтримки для збирання сміття.

To create a container type, the tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC and provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear implementation must also be provided.

Py_TPFLAGS_HAVE_GC

Об’єкти типу з цим прапорцем мають відповідати задокументованим тут правилам. Для зручності ці об’єкти будуть називатися об’єктами-контейнерами.

Конструктори для типів контейнерів повинні відповідати двом правилам:

  1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.

  2. Після ініціалізації всіх полів, які можуть містити посилання на інші контейнери, він повинен викликати PyObject_GC_Track().

Подібним чином, делокатор для об’єкта має відповідати подібній парі правил:

  1. Перш ніж поля, які посилаються на інші контейнери, стануть недійсними, необхідно викликати PyObject_GC_UnTrack().

  2. Пам’ять об’єкта має бути звільнено за допомогою PyObject_GC_Del().

    Попередження

    Якщо тип додає Py_TPFLAGS_HAVE_GC, тоді він має реалізувати принаймні обробник tp_traverse або явно використовувати один із свого підкласу або підкласів.

    When calling PyType_Ready() or some of the APIs that indirectly call it like PyType_FromSpecWithBases() or PyType_FromSpec() the interpreter will automatically populate the tp_flags, tp_traverse and tp_clear fields if the type inherits from a class that implements the garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC flag.

PyObject_GC_New(TYPE, typeobj)

Analogous to PyObject_New but for container objects with the Py_TPFLAGS_HAVE_GC flag set.

Do not call this directly to allocate memory for an object; call the type’s tp_alloc slot instead.

When populating a type’s tp_alloc slot, PyType_GenericAlloc() is preferred over a custom function that simply calls this macro.

Memory allocated by this macro must be freed with PyObject_GC_Del() (usually called via the object’s tp_free slot).

PyObject_GC_NewVar(TYPE, typeobj, size)

Analogous to PyObject_NewVar but for container objects with the Py_TPFLAGS_HAVE_GC flag set.

Do not call this directly to allocate memory for an object; call the type’s tp_alloc slot instead.

When populating a type’s tp_alloc slot, PyType_GenericAlloc() is preferred over a custom function that simply calls this macro.

Memory allocated by this macro must be freed with PyObject_GC_Del() (usually called via the object’s tp_free slot).

PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
This is Unstable API. It may change without warning in minor releases.

Analogous to PyObject_GC_New but allocates extra_size bytes at the end of the object (at offset tp_basicsize). The allocated memory is initialized to zeros, except for the Python object header.

The extra data will be deallocated with the object, but otherwise it is not managed by Python.

Memory allocated by this function must be freed with PyObject_GC_Del() (usually called via the object’s tp_free slot).

Попередження

The function is marked as unstable because the final mechanism for reserving extra data after an instance is not yet decided. For allocating a variable number of fields, prefer using PyVarObject and tp_itemsize instead.

Added in version 3.12.

PyObject_GC_Resize(TYPE, op, newsize)

Resize an object allocated by PyObject_NewVar. Returns the resized object of type TYPE* (refers to any C type) or NULL on failure.

op must be of type PyVarObject* and must not be tracked by the collector yet. newsize must be of type Py_ssize_t.

void PyObject_GC_Track(PyObject *op)
Part of the Stable ABI.

Додає об’єкт op до набору об’єктів-контейнерів, які відстежує збирач. Збирач може запускатися в несподіваний час, тому об’єкти мають бути дійсними під час відстеження. Його слід викликати, коли всі поля, за якими йде обробник tp_traverse, стануть дійсними, як правило, ближче до кінця конструктора.

int PyObject_IS_GC(PyObject *obj)

Повертає ненульове значення, якщо об’єкт реалізує протокол збирача сміття, інакше повертає 0.

Збирач сміття не може відстежувати об’єкт, якщо ця функція повертає 0.

int PyObject_GC_IsTracked(PyObject *op)
Part of the Stable ABI since version 3.9.

Повертає 1, якщо тип об’єкта op реалізує протокол GC і op зараз відстежується збирачем сміття, і 0 в іншому випадку.

Це аналогічно функції Python gc.is_tracked().

Added in version 3.9.

int PyObject_GC_IsFinalized(PyObject *op)
Part of the Stable ABI since version 3.9.

Повертає 1, якщо тип об’єкта op реалізує протокол GC і op вже завершено збирачем сміття, і 0 в іншому випадку.

Це аналогічно функції Python gc.is_finalized().

Added in version 3.9.

void PyObject_GC_Del(void *op)
Part of the Stable ABI.

Releases memory allocated to an object using PyObject_GC_New or PyObject_GC_NewVar.

Do not call this directly to free an object’s memory; call the type’s tp_free slot instead.

Do not use this for memory allocated by PyObject_New, PyObject_NewVar, or related allocation functions; use PyObject_Free() instead.

Дивись також

void PyObject_GC_UnTrack(void *op)
Part of the Stable ABI.

Видаліть об’єкт op із набору об’єктів-контейнерів, які відстежує збирач. Зауважте, що PyObject_GC_Track() можна знову викликати для цього об’єкта, щоб додати його назад до набору відстежуваних об’єктів. Deallocator (tp_dealloc обробник) має викликати це для об’єкта до того, як будь-яке з полів, що використовуються tp_traverse обробником, стане недійсним.

Змінено в версії 3.8: The _PyObject_GC_TRACK() and _PyObject_GC_UNTRACK() macros have been removed from the public C API.

Обробник tp_traverse приймає параметр функції такого типу:

typedef int (*visitproc)(PyObject *object, void *arg)
Part of the Stable ABI.

Тип функції відвідувача, переданої обробнику tp_traverse. Функція має бути викликана з об’єктом для проходження як object і третім параметром для обробника tp_traverse як arg. Ядро Python використовує кілька функцій відвідувачів для реалізації циклічного виявлення сміття; не очікується, що користувачам доведеться писати власні функції відвідувачів.

Обробник tp_clear має бути типу inquiry або NULL, якщо об’єкт є незмінним.

typedef int (*inquiry)(PyObject *self)
Part of the Stable ABI.

Видалити посилання, які могли створити цикли посилань. Незмінні об’єкти не повинні визначати цей метод, оскільки вони ніколи не можуть безпосередньо створювати еталонні цикли. Зауважте, що об’єкт все ще має бути дійсним після виклику цього методу (не просто викликайте Py_DECREF() за посиланням). Збирач викличе цей метод, якщо виявить, що цей об’єкт бере участь у еталонному циклі.

Traversal

Обробник tp_traverse повинен мати такий тип:

typedef int (*traverseproc)(PyObject *self, visitproc visit, void *arg)
Part of the Stable ABI.

Traversal function for a garbage-collected object, used by the garbage collector to detect reference cycles. Implementations must call the visit function for each object directly contained by self, with the parameters to visit being the contained object and the arg value passed to the handler. The visit function must not be called with a NULL object argument. If visit returns a non-zero value, that value should be returned immediately.

A typical tp_traverse function calls the Py_VISIT() convenience macro on each of the instance’s members that are Python objects that the instance owns. For example, this is a (slightly outdated) traversal function for the threading.local class:

static int
local_traverse(PyObject *op, visitproc visit, void *arg)
{
    localobject *self = (localobject *) op;
    Py_VISIT(Py_TYPE(self));
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
}

Примітка

Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific names; don’t name them just anything.

Instances of heap-allocated types hold a reference to their type. Their traversal function must therefore visit the type:

Py_VISIT(Py_TYPE(self));

Alternately, the type may delegate this responsibility by calling tp_traverse of a heap-allocated superclass (or another heap-allocated type, if applicable). If they do not, the type object may not be garbage-collected.

If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call PyObject_VisitManagedDict() like this:

int err = PyObject_VisitManagedDict((PyObject*)self, visit, arg);
if (err) {
    return err;
}

Only the members that the instance owns (by having strong references to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot, the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does not directly own the weak references to itself.

The traversal function has a limitation:

Попередження

The traversal function must not have any side effects. Implementations may not modify the reference counts of any Python objects nor create or destroy any Python objects, directly or indirectly.

This means that most Python C API functions may not be used, since they can raise a new exception, return a new reference to a result object, have internal logic that uses side effects. Also, unless documented otherwise, functions that happen to not have side effects may start having them in future versions, without warning.

For a list of safe functions, see a separate section below.

Примітка

The Py_VISIT() call may be skipped for those members that provably cannot participate in reference cycles. In the local_traverse example above, there is also a self->key member, but it can only be NULL or a Python string and therefore cannot be part of a reference cycle.

On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want to visit it anyway just so the gc module’s get_referents() function will include it.

Примітка

The tp_traverse function can be called from any thread.

Деталі реалізації CPython: Garbage collection is a «stop-the-world» operation: even in free threading builds, only one thread state is attached when tp_traverse handlers run.

Змінено в версії 3.9: Heap-allocated types are expected to visit Py_TYPE(self) in tp_traverse. In earlier versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.

To simplify writing tp_traverse handlers, a Py_VISIT() macro is provided. In order to use this macro, the tp_traverse implementation must name its arguments exactly visit and arg:

Py_VISIT(o)

If the PyObject* o is not NULL, call the visit callback, with arguments o and arg. If visit returns a non-zero value, then return it.

This corresponds roughly to:

#define Py_VISIT(o)                             \
   if (op) {                                    \
      int visit_result = visit(o, arg);         \
      if (visit_result != 0) {                  \
         return visit_result;                   \
      }                                         \
   }

Traversal-safe functions

The following functions and macros are safe to use in a tp_traverse handler:

«DuringGC» functions

The following functions should only be used in a tp_traverse handler; calling them in other contexts may have unintended consequences.

These functions act like their counterparts without the _DuringGC suffix, but they are guaranteed to not have side effects, they do not set an exception on failure, and they return/set borrowed references as detailed in the individual documentation.

Note that these functions may fail (return NULL or -1), but as they do not set an exception, no error information is available. In some cases, failure is not distinguishable from a successful NULL result.

void *PyObject_GetTypeData_DuringGC(PyObject *o, PyTypeObject *cls)
void *PyObject_GetItemData_DuringGC(PyObject *o)
void *PyType_GetModuleState_DuringGC(PyTypeObject *type)
void *PyModule_GetState_DuringGC(PyObject *module)
int PyModule_GetToken_DuringGC(PyObject *module, void **result)
Part of the Stable ABI since version 3.15.

See «DuringGC» functions for common information.

Added in version 3.15.0a8 (unreleased).

int PyType_GetBaseByToken_DuringGC(PyTypeObject *type, void *tp_token, PyTypeObject **result)
Part of the Stable ABI since version 3.15.

See «DuringGC» functions for common information.

Sets *result to a borrowed reference rather than a strong one. The reference is valid for the duration of the tp_traverse handler call.

Added in version 3.15.0a8 (unreleased).

Дивись також

PyType_GetBaseByToken()

PyObject *PyType_GetModule_DuringGC(PyTypeObject *type)
PyObject *PyType_GetModuleByToken_DuringGC(PyTypeObject *type, const void *mod_token)
Return value: Borrowed reference. Part of the Stable ABI since version 3.15.

See «DuringGC» functions for common information.

These functions return a borrowed reference, which is valid for the duration of the tp_traverse handler call.

Added in version 3.15.0a8 (unreleased).

Контроль стану Garbage Collector

C-API надає такі функції для керування виконанням збирання сміття.

Py_ssize_t PyGC_Collect(void)
Part of the Stable ABI.

Виконати повне збирання сміття, якщо ввімкнено збирач сміття. (Зверніть увагу, що gc.collect() запускає його безумовно.)

Повертає кількість зібраних + недосяжних об’єктів, які неможливо зібрати. Якщо збирач сміття вимкнено або вже збирає, негайно повертає 0. Помилки під час збирання сміття передаються до sys.unraisablehook. Ця функція не викликає винятків.

int PyGC_Enable(void)
Part of the Stable ABI since version 3.10.

Увімкніть збирач сміття: подібно до gc.enable(). Повертає попередній стан, 0 для вимкнено та 1 для ввімкнено.

Added in version 3.10.

int PyGC_Disable(void)
Part of the Stable ABI since version 3.10.

Вимкнути збирач сміття: подібно до gc.disable(). Повертає попередній стан, 0 для вимкнено та 1 для ввімкнено.

Added in version 3.10.

int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10.

Запитайте стан збирача сміття: подібно до gc.isenabled(). Повертає поточний стан, 0 для вимкнено та 1 для ввімкнено.

Added in version 3.10.

Querying Garbage Collector State

The C-API provides the following interface for querying information about the garbage collector.

void PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
This is Unstable API. It may change without warning in minor releases.

Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.

Попередження

If new objects are (de)allocated by the callback it is undefined if they will be visited.

Garbage collection is disabled during operation. Explicitly running a collection in the callback may lead to undefined behaviour e.g. visiting the same objects multiple times or not at all.

Added in version 3.12.

typedef int (*gcvisitobjects_t)(PyObject *object, void *arg)

Type of the visitor function to be passed to PyUnstable_GC_VisitObjects(). arg is the same as the arg passed to PyUnstable_GC_VisitObjects. Return 1 to continue iteration, return 0 to stop iteration. Other return values are reserved for now so behavior on returning anything else is undefined.

Added in version 3.12.