Type Object Structures

Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the PyTypeObject structure. Type objects can be handled using any of the PyObject_* or PyType_* functions, but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects behave, so they are very important to the interpreter itself and to any extension module that implements new types.

Об’єкти типу досить великі порівняно з більшістю стандартних типів. Причина такого розміру полягає в тому, що кожен об’єкт типу зберігає велику кількість значень, переважно покажчиків на функції C, кожен з яких реалізує невелику частину функціональності типу. У цьому розділі детально розглядаються поля об’єкта типу. Поля будуть описані в тому порядку, в якому вони розташовані в структурі.

На додаток до наведеної нижче короткої довідки, розділ Приклади надає швидке розуміння значення та використання PyTypeObject.

Короткий довідник

«tp слоти»

Слот PyTypeObject [1]

Введіть

спеціальні методи/атр

Інформація [2]

О

T

D

I

<R> tp_name

const char *

__name__

X

X

tp_basicsize

Py_ssize_t

X

X

X

tp_itemsize

Py_ssize_t

X

X

tp_dealloc

destructor

X

X

X

tp_vectorcall_offset

Py_ssize_t

X

X

(tp_getattr)

getattrfunc

__getattribute__, __getattr__

Г

(tp_setattr)

setattrfunc

__setattr__, __delattr__

Г

tp_as_async

PyAsyncMethods *

підслоти

%

tp_repr

reprfunc

__repr__

X

X

X

tp_as_number

PyNumberMethods *

підслоти

%

tp_as_sequence

PySequenceMethods *

підслоти

%

tp_as_mapping

PyMappingMethods *

підслоти

%

tp_hash

hashfunc

__hash__

X

Г

tp_call

ternaryfunc

__call__

X

X

tp_str

reprfunc

__str__

X

X

tp_getattro

getattrofunc

__getattribute__, __getattr__

X

X

Г

tp_setattro

setattrofunc

__setattr__, __delattr__

X

X

Г

tp_as_buffer

PyBufferProcs *

підслоти

%

tp_flags

беззнаковий long

X

X

?

tp_doc

const char *

__doc__

X

X

tp_traverse

traverseproc

X

Г

tp_clear

inquiry

X

Г

tp_richcompare

richcmpfunc

__lt__, __le__, __eq__, __ne__, __gt__, __ge__

X

Г

(tp_weaklistoffset)

Py_ssize_t

X

?

tp_iter

getiterfunc

__iter__

X

tp_iternext

iternextfunc

__next__

X

tp_methods

PyMethodDef []

X

X

tp_members

PyMemberDef []

X

tp_getset

PyGetSetDef []

X

X

tp_base

PyTypeObject *

__base__

X

tp_dict

PyObject *

__dict__

?

tp_descr_get

descrgetfunc

__get__

X

tp_descr_set

descrsetfunc

__set__, __delete__

X

(tp_dictoffset)

Py_ssize_t

X

?

tp_init

initproc

__init__

X

X

X

tp_alloc

allocfunc

X

?

?

tp_new

newfunc

__new__

X

X

?

?

tp_free

freefunc

X

X

?

?

tp_is_gc

inquiry

X

X

<tp_bases>

PyObject *

__bases__

~

<tp_mro>

PyObject *

__mro__

~

[tp_cache]

PyObject *

[tp_subclasses]

порожній *

__subclasses__

[tp_weaklist]

PyObject *

(tp_del)

destructor

[tp_version_tag]

беззнаковий int

tp_finalize

destructor

__del__

X

tp_vectorcall

vectorcallfunc

[tp_watched]

беззнаковий символ

підслоти

Слот

Введіть

спеціальні методи

am_await

unaryfunc

__await__

am_aiter

unaryfunc

__aiter__

am_anext

unaryfunc

__anext__

am_send

sendfunc

nb_add

binaryfunc

__add__ __radd__

nb_inplace_add

binaryfunc

__iadd__

nb_subtract

binaryfunc

__sub__ __rsub__

nb_inplace_subtract

binaryfunc

__isub__

nb_multiply

binaryfunc

__mul__ __rmul__

nb_inplace_multiply

binaryfunc

__imul__

nb_remainder

binaryfunc

__mod__ __rmod__

nb_inplace_remainder

binaryfunc

__imod__

nb_divmod

binaryfunc

__divmod__ __rdivmod__

nb_power

ternaryfunc

__pow__ __rpow__

nb_inplace_power

ternaryfunc

__ipow__

nb_negative

unaryfunc

__neg__

nb_positive

unaryfunc

__pos__

nb_absolute

unaryfunc

__abs__

nb_bool

inquiry

__bool__

nb_invert

unaryfunc

__invert__

nb_lshift

binaryfunc

__lshift__ __rlshift__

nb_inplace_lshift

binaryfunc

__ilshift__

nb_rshift

binaryfunc

__rshift__ __rrshift__

nb_inplace_rshift

binaryfunc

__irshift__

nb_and

binaryfunc

__and__ __rand__

nb_inplace_and

binaryfunc

__iand__

nb_xor

binaryfunc

__xor__ __rxor__

nb_inplace_xor

binaryfunc

__ixor__

nb_or

binaryfunc

__or__ __ror__

nb_inplace_or

binaryfunc

__ior__

nb_int

unaryfunc

__int__

nb_reserved

порожній *

nb_float

unaryfunc

__float__

nb_floor_divide

binaryfunc

__floordiv__

nb_inplace_floor_divide

binaryfunc

__ifloordiv__

nb_true_divide

binaryfunc

__truediv__

nb_inplace_true_divide

binaryfunc

__itruediv__

nb_index

unaryfunc

__index__

nb_matrix_multiply

binaryfunc

__matmul__ __rmatmul__

nb_inplace_matrix_multiply

binaryfunc

__imatmul__

mp_length

lenfunc

__len__

mp_subscript

binaryfunc

__getitem__

mp_ass_subscript

objobjargproc

__setitem__, __delitem__

sq_length

lenfunc

__len__

sq_concat

binaryfunc

__add__

sq_repeat

ssizeargfunc

__mul__

sq_item

ssizeargfunc

__getitem__

sq_ass_item

ssizeobjargproc

__setitem__ __delitem__

sq_contains

objobjproc

__contains__

sq_inplace_concat

binaryfunc

__iadd__

sq_inplace_repeat

ssizeargfunc

__imul__

bf_getbuffer

getbufferproc()

__buffer__

bf_releasebuffer

releasebufferproc()

__release_buffer__

типи слотів

typedef

Типи параметрів

Тип повернення

allocfunc

PyObject *

destructor

PyObject *

пустий

freefunc

порожній *

пустий

traverseproc

порожній *

int

newfunc

PyObject *

initproc

int

reprfunc

PyObject *

PyObject *

getattrfunc

const char *

PyObject *

setattrfunc

const char *

int

getattrofunc

PyObject *

setattrofunc

int

descrgetfunc

PyObject *

descrsetfunc

int

hashfunc

PyObject *

Py_hash_t

richcmpfunc

int

PyObject *

getiterfunc

PyObject *

PyObject *

iternextfunc

PyObject *

PyObject *

lenfunc

PyObject *

Py_ssize_t

getbufferproc

int

releasebufferproc

пустий

inquiry

PyObject *

int

unaryfunc

PyObject *

binaryfunc

PyObject *

ternaryfunc

PyObject *

ssizeargfunc

PyObject *

ssizeobjargproc

int

objobjproc

int

objobjargproc

int

Дивіться Типи слотів нижче, щоб дізнатися більше.

Визначення PyTypeObject

The structure definition for PyTypeObject can be found in Include/cpython/object.h. For convenience of reference, this repeats the definition found there:

typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    PyMethodDef *tp_methods;
    PyMemberDef *tp_members;
    PyGetSetDef *tp_getset;
    // Strong reference on a heap type, borrowed reference on a static type
    PyTypeObject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache; /* no longer used */
    void *tp_subclasses;  /* for static builtin types this is an index */
    PyObject *tp_weaklist; /* not used for static builtin types */
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6.
     * If zero, the cache is invalid and must be initialized.
     */
    unsigned int tp_version_tag;

    destructor tp_finalize;
    vectorcallfunc tp_vectorcall;

    /* bitset of which type-watchers care about this type */
    unsigned char tp_watched;

    /* Number of tp_version_tag values used.
     * Set to _Py_ATTR_CACHE_UNUSED if the attribute cache is
     * disabled for this type (e.g. due to custom MRO entries).
     * Otherwise, limited to MAX_VERSIONS_PER_CLASS (defined elsewhere).
     */
    uint16_t tp_versions_used;
} PyTypeObject;

Слоти PyObject

The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (created by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.

PyObject.ob_refcnt

The type object’s reference count is initialized to 1 by the PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type’s instances (objects whose ob_type points back to the type) do not count as references. But for dynamically allocated type objects, the instances do count as references.

Наслідування:

Це поле не успадковується підтипами.

PyObject.ob_type

Це тип типу, іншими словами його метатип. Він ініціалізується аргументом макросу PyObject_HEAD_INIT, і його значення зазвичай має бути &PyType_Type. Однак для динамічно завантажуваних модулів розширення, які повинні використовуватися в Windows (принаймні), компілятор скаржиться, що це недійсний ініціалізатор. Таким чином, прийнято передавати NULL в макрос PyObject_HEAD_INIT і ініціалізувати це поле явно на початку функції ініціалізації модуля, перш ніж робити будь-що інше. Зазвичай це робиться так:

Foo_Type.ob_type = &PyType_Type;

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this field if it is non-zero.

Наслідування:

Це поле успадковується підтипами.

Слоти PyVarObject

PyVarObject.ob_size

Для статично виділених об’єктів типу, це має бути ініціалізовано нулем. Для динамічно виділених об’єктів типу це поле має особливе внутрішнє значення.

This field should be accessed using the Py_SIZE() macro.

Наслідування:

Це поле не успадковується підтипами.

Слоти PyTypeObject

Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to NULL then there will also be a «Default» section. (Note that many fields set on PyBaseObject_Type and PyType_Type effectively act as defaults.)

const char *PyTypeObject.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should be just the type name. If the module is a submodule of a package, the full package name is part of the full module name. For example, a type named T defined in module M in subpackage Q in package P should have the tp_name initializer "P.Q.M.T".

Для динамічно виділених об’єктів типу, це має бути лише ім’я типу, а ім’я модуля явно зберігається в dict типу як значення для ключа '__module__'.

For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot is made accessible as the __module__ attribute, and everything after the last dot is made accessible as the __name__ attribute.

If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the __module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This means your type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc.

Це поле не має бути NULL. Це єдине обов’язкове поле в PyTypeObject() (окрім потенційно tp_itemsize).

Наслідування:

Це поле не успадковується підтипами.

Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize

Ці поля дозволяють обчислити розмір екземплярів типу в байтах.

There are two kinds of types: types with fixed-length instances have a zero tp_itemsize field, types with variable-length instances have a non-zero tp_itemsize field. For a type with fixed-length instances, all instances have the same size, given in tp_basicsize. (Exceptions to this rule can be made using PyUnstable_Object_GC_NewWithExtraData().)

For a type with variable-length instances, the instances must have an ob_size field, and the instance size is tp_basicsize plus N times tp_itemsize, where N is the «length» of the object.

Functions like PyObject_NewVar() will take the value of N as an argument, and store in the instance’s ob_size field. Note that the ob_size field may later be used for other purposes. For example, int instances use the bits of ob_size in an implementation-defined way; the underlying storage and its size should be accessed using PyLong_Export().

Примітка

The ob_size field should be accessed using the Py_SIZE() and Py_SET_SIZE() macros.

Also, the presence of an ob_size field in the instance layout doesn’t mean that the instance structure is variable-length. For example, the list type has fixed-length instances, yet those instances have a ob_size field. (As with int, avoid reading lists“ ob_size directly. Call PyList_Size() instead.)

The tp_basicsize includes size needed for data of the type’s tp_base, plus any extra data needed by each instance.

The correct way to set tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. This struct must include the struct used to declare the base type. In other words, tp_basicsize must be greater than or equal to the base’s tp_basicsize.

Since every type is a subtype of object, this struct must include PyObject or PyVarObject (depending on whether ob_size should be included). These are usually defined by the macro PyObject_HEAD or PyObject_VAR_HEAD, respectively.

The basic size does not include the GC header size, as that header is not part of PyObject_HEAD.

For cases where struct used to declare the base type is unknown, see PyType_Spec.basicsize and PyType_FromMetaclass().

Notes about alignment:

  • tp_basicsize must be a multiple of _Alignof(PyObject). When using sizeof on a struct that includes PyObject_HEAD, as recommended, the compiler ensures this. When not using a C struct, or when using compiler extensions like __attribute__((packed)), it is up to you.

  • If the variable items require a particular alignment, tp_basicsize and tp_itemsize must each be a multiple of that alignment. For example, if a type’s variable part stores a double, it is your responsibility that both fields are a multiple of _Alignof(double).

Наслідування:

These fields are inherited separately by subtypes. (That is, if the field is set to zero, PyType_Ready() will copy the value from the base type, indicating that the instances do not need additional storage.)

If the base type has a non-zero tp_itemsize, it is generally not safe to set tp_itemsize to a different non-zero value in a subtype (though this depends on the implementation of the base type).

destructor PyTypeObject.tp_dealloc

A pointer to the instance destructor function. The function signature is:

void tp_dealloc(PyObject *self);

The destructor function should remove all references which the instance owns (e.g., call Py_CLEAR()), free all memory buffers owned by the instance, and call the type’s tp_free function to free the object itself.

If you may call functions that may set the error indicator, you must use PyErr_GetRaisedException() and PyErr_SetRaisedException() to ensure you don’t clobber a preexisting error indicator (the deallocation could have occurred while processing a different error):

static void
foo_dealloc(foo_object *self)
{
    PyObject *et, *ev, *etb;
    PyObject *exc = PyErr_GetRaisedException();
    ...
    PyErr_SetRaisedException(exc);
}

The dealloc handler itself must not raise an exception; if it hits an error case it should call PyErr_FormatUnraisable() to log (and clear) an unraisable exception.

No guarantees are made about when an object is destroyed, except:

  • Python will destroy an object immediately or some time after the final reference to the object is deleted, unless its finalizer (tp_finalize) subsequently resurrects the object.

  • An object will not be destroyed while it is being automatically finalized (tp_finalize) or automatically cleared (tp_clear).

CPython currently destroys an object immediately from Py_DECREF() when the new reference count is zero, but this may change in a future version.

It is recommended to call PyObject_CallFinalizerFromDealloc() at the beginning of tp_dealloc to guarantee that the object is always finalized before destruction.

If the type supports garbage collection (the Py_TPFLAGS_HAVE_GC flag is set), the destructor should call PyObject_GC_UnTrack() before clearing any member fields.

It is permissible to call tp_clear from tp_dealloc to reduce code duplication and to guarantee that the object is always cleared before destruction. Beware that tp_clear might have already been called.

If the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned reference to its type object (via Py_DECREF()) after calling the type deallocator. See the example code below.:

static void
foo_dealloc(PyObject *op)
{
   foo_object *self = (foo_object *) op;
   PyObject_GC_UnTrack(self);
   Py_CLEAR(self->ref);
   Py_TYPE(self)->tp_free(self);
}

tp_dealloc must leave the exception status unchanged. If it needs to call something that might raise an exception, the exception state must be backed up first and restored later (after logging any exceptions with PyErr_WriteUnraisable()).

Example:

static void
foo_dealloc(PyObject *self)
{
    PyObject *exc = PyErr_GetRaisedException();

    if (PyObject_CallFinalizerFromDealloc(self) < 0) {
        // self was resurrected.
        goto done;
    }

    PyTypeObject *tp = Py_TYPE(self);

    if (tp->tp_flags & Py_TPFLAGS_HAVE_GC) {
        PyObject_GC_UnTrack(self);
    }

    // Optional, but convenient to avoid code duplication.
    if (tp->tp_clear && tp->tp_clear(self) < 0) {
        PyErr_WriteUnraisable(self);
    }

    // Any additional destruction goes here.

    tp->tp_free(self);
    self = NULL;  // In case PyErr_WriteUnraisable() is called below.

    if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) {
        Py_CLEAR(tp);
    }

done:
    // Optional, if something was called that might have raised an
    // exception.
    if (PyErr_Occurred()) {
        PyErr_WriteUnraisable(self);
    }
    PyErr_SetRaisedException(exc);
}

tp_dealloc may be called from any Python thread, not just the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which tp_dealloc is called with an attached thread state. However, if the object being destroyed in turn destroys objects from some other C library, care should be taken to ensure that destroying those objects on the thread which called tp_dealloc will not violate any assumptions of the library.

Наслідування:

Це поле успадковується підтипами.

Дивись також

Object Life Cycle for details about how this slot relates to other slots.

Py_ssize_t PyTypeObject.tp_vectorcall_offset

Необов’язкове зміщення функції для кожного екземпляра, яка реалізує виклик об’єкта за допомогою vectorcall протоколу, більш ефективної альтернативи простішого tp_call.

This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive integer containing the offset in the instance of a vectorcallfunc pointer.

The vectorcallfunc pointer may be NULL, in which case the instance behaves as if Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.

Будь-який клас, який встановлює Py_TPFLAGS_HAVE_VECTORCALL, також повинен встановити tp_call і переконатися, що його поведінка узгоджується з функцією vectorcallfunc. Це можна зробити, встановивши tp_call на PyVectorcall_Call().

Змінено в версії 3.8: До версії 3.8 цей слот мав назву tp_print. У Python 2.x він використовувався для друку у файл. У Python від 3.0 до 3.7 він не використовувався.

Змінено в версії 3.12: Before version 3.12, it was not recommended for mutable heap types to implement the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization by clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.

Наслідування:

This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly called.

getattrfunc PyTypeObject.tp_getattr

Додатковий покажчик на функцію get-attribute-string.

Це поле застаріло. Коли його визначено, він має вказувати на функцію, яка діє так само, як функція tp_getattro, але використовує рядок C замість рядкового об’єкта Python, щоб надати назву атрибуту.

Наслідування:

Group: tp_getattr, tp_getattro

Це поле успадковується підтипами разом із tp_getattro: підтип успадковує і tp_getattr, і tp_getattro від своєї основи типу, коли підтипи tp_getattr і tp_getattro мають значення NULL.

setattrfunc PyTypeObject.tp_setattr

Додатковий вказівник на функцію для налаштування та видалення атрибутів.

Це поле застаріло. Коли його визначено, він має вказувати на функцію, яка діє так само, як функція tp_setattro, але використовує рядок C замість рядкового об’єкта Python, щоб надати назву атрибуту.

Наслідування:

Group: tp_setattr, tp_setattro

Це поле успадковується підтипами разом із tp_setattro: підтип успадковує і tp_setattr, і tp_setattro від своєї основи типу, коли підтипи tp_setattr і tp_setattro мають значення NULL.

PyAsyncMethods *PyTypeObject.tp_as_async

Покажчик на додаткову структуру, яка містить поля, що стосуються лише об’єктів, які реалізують протоколи awaitable і asynchronous iterator на рівні C. Дивіться Асинхронні об’єктні структури для деталей.

Added in version 3.5: Раніше відомий як tp_compare і tp_reserved.

Наслідування:

Поле tp_as_async не успадковується, але поля, що містяться, успадковуються окремо.

reprfunc PyTypeObject.tp_repr

Додатковий покажчик на функцію, яка реалізує вбудовану функцію repr().

Підпис такий самий, як і для PyObject_Repr():

PyObject *tp_repr(PyObject *self);

Функція має повертати рядок або об’єкт Unicode. В ідеалі ця функція має повертати рядок, який, переданий до eval(), за відповідного середовища повертає об’єкт із тим самим значенням. Якщо це неможливо, він повинен повертати рядок, що починається з '<' та закінчується на '>', з якого можна вивести як тип, так і значення об’єкта.

Наслідування:

Це поле успадковується підтипами.

За замовчуванням:

Якщо це поле не встановлено, повертається рядок у формі <%s object at %p>, де %s замінюється назвою типу, а %p адресою пам’яті об’єкта.

PyNumberMethods *PyTypeObject.tp_as_number

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

Наслідування:

Поле tp_as_number не успадковується, але поля, що містяться, успадковуються окремо.

PySequenceMethods *PyTypeObject.tp_as_sequence

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

Наслідування:

Поле tp_as_sequence не успадковується, але поля, що містяться, успадковуються окремо.

PyMappingMethods *PyTypeObject.tp_as_mapping

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

Наслідування:

Поле tp_as_mapping не успадковується, але поля, що містяться, успадковуються окремо.

hashfunc PyTypeObject.tp_hash

Додатковий покажчик на функцію, яка реалізує вбудовану функцію hash().

Підпис такий самий, як і для PyObject_Hash():

Py_hash_t tp_hash(PyObject *);

Значення -1 не повинно повертатися як звичайне значення, що повертається; якщо під час обчислення хеш-значення виникає помилка, функція повинна встановити виняток і повернути -1.

When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises TypeError. This is the same as setting it to PyObject_HashNotImplemented().

У цьому полі можна явно встановити значення PyObject_HashNotImplemented(), щоб заблокувати успадкування геш-методу від батьківського типу. Це інтерпретується як еквівалент __hash__ = None на рівні Python, змушуючи isinstance(o, collections.Hashable) правильно повертати False. Зауважте, що зворотне також вірно – встановлення __hash__ = None для класу на рівні Python призведе до того, що слот tp_hash буде встановлено на PyObject_HashNotImplemented().

Наслідування:

Group: tp_hash, tp_richcompare

Це поле успадковується підтипами разом із tp_richcompare: підтип успадковує як tp_richcompare, так і tp_hash, коли підтипи tp_richcompare і tp_hash мають значення NULL.

За замовчуванням:

PyBaseObject_Type uses PyObject_GenericHash().

ternaryfunc PyTypeObject.tp_call

Додатковий покажчик на функцію, яка реалізує виклик об’єкта. Це має бути NULL, якщо об’єкт не можна викликати. Підпис такий самий, як і для PyObject_Call():

PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

Наслідування:

Це поле успадковується підтипами.

reprfunc PyTypeObject.tp_str

Додатковий покажчик на функцію, яка реалізує вбудовану операцію str(). (Зауважте, що str тепер є типом, а str() викликає конструктор для цього типу. Цей конструктор викликає PyObject_Str() для виконання фактичної роботи, а PyObject_Str() викличе цей обробник.)

Підпис такий самий, як і для PyObject_Str():

PyObject *tp_str(PyObject *self);

Функція має повертати рядок або об’єкт Unicode. Це має бути «дружнє» рядкове представлення об’єкта, оскільки це представлення буде використовуватися, серед іншого, функцією print().

Наслідування:

Це поле успадковується підтипами.

За замовчуванням:

Якщо це поле не встановлено, PyObject_Repr() викликається для повернення рядкового представлення.

getattrofunc PyTypeObject.tp_getattro

Додатковий покажчик на функцію get-attribute.

Підпис такий самий, як і для PyObject_GetAttr():

PyObject *tp_getattro(PyObject *self, PyObject *attr);

Зазвичай зручно встановити для цього поля значення PyObject_GenericGetAttr(), що реалізує звичайний спосіб пошуку атрибутів об’єкта.

Наслідування:

Group: tp_getattr, tp_getattro

Це поле успадковується підтипами разом із tp_getattr: підтип успадковує і tp_getattr, і tp_getattro від своєї основи типу, коли підтипи tp_getattr і tp_getattro мають значення NULL.

За замовчуванням:

PyBaseObject_Type uses PyObject_GenericGetAttr().

setattrofunc PyTypeObject.tp_setattro

Додатковий вказівник на функцію для налаштування та видалення атрибутів.

Підпис такий самий, як і для PyObject_SetAttr():

int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

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

Наслідування:

Group: tp_setattr, tp_setattro

Це поле успадковується підтипами разом із tp_setattr: підтип успадковує і tp_setattr, і tp_setattro від своєї основи типу, коли підтипи tp_setattr і tp_setattro мають значення NULL.

За замовчуванням:

PyBaseObject_Type uses PyObject_GenericSetAttr().

PyBufferProcs *PyTypeObject.tp_as_buffer

Покажчик на додаткову структуру, яка містить поля, що стосуються лише об’єктів, які реалізують інтерфейс буфера. Ці поля задокументовані в Буферні об’єктні структури.

Наслідування:

Поле tp_as_buffer не успадковується, але поля, що містяться, успадковуються окремо.

unsigned long PyTypeObject.tp_flags

Це поле є бітовою маскою різних прапорів. Деякі прапорці вказують на варіантну семантику для певних ситуацій; інші використовуються для вказівки, що певні поля в об’єкті типу (або в структурах розширення, на які посилаються через tp_as_number, tp_as_sequence, tp_as_mapping і tp_as_buffer), які історично не завжди були присутні, є дійсними; якщо такий біт прапора очищений, до полів типу, які він охороняє, не можна звертатися, і вони повинні вважатися такими, що мають нульове або NULL значення.

Наслідування:

Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values.

За замовчуванням:

PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.

Бітові маски:

Наразі визначено такі бітові маски; їх можна об’єднати АБО за допомогою оператора |, щоб сформувати значення поля tp_flags. Макрос PyType_HasFeature() приймає тип і значення прапорців, tp і f, і перевіряє, чи tp->tp_flags & f є відмінним від нуля.

Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap, for example, types created dynamically using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance’s ob_type gets INCREF’ed or DECREF’ed). Heap types should also support garbage collection as they can form a reference cycle with their own module object.

Наслідування:

???

Py_TPFLAGS_BASETYPE

Цей біт встановлюється, коли тип можна використовувати як базовий тип іншого типу. Якщо цей біт ясний, тип не може бути підтиповим (подібно до «фінального» класу в Java).

Наслідування:

???

Py_TPFLAGS_READY

Цей біт встановлюється, коли об’єкт типу повністю ініціалізовано PyType_Ready().

Наслідування:

???

Py_TPFLAGS_READYING

Цей біт встановлюється, коли PyType_Ready() знаходиться в процесі ініціалізації об’єкта типу.

Наслідування:

???

Py_TPFLAGS_HAVE_GC

This bit is set when the object supports garbage collection. If this bit is set, memory for new instances (see tp_alloc) must be allocated using PyObject_GC_New or PyType_GenericAlloc() and deallocated (see tp_free) using PyObject_GC_Del(). More information in section Підтримка циклічного збирання сміття.

Наслідування:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values.

Py_TPFLAGS_DEFAULT

This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.

Наслідування:

???

Py_TPFLAGS_METHOD_DESCRIPTOR

Цей біт вказує, що об’єкти поводяться як незв’язані методи.

Якщо цей прапор встановлено для type(meth), тоді:

  • meth.__get__(obj, cls)(*args, **kwds)obj не None) має бути еквівалентним meth(obj, *args, **kwds).

  • meth.__get__(None, cls)(*args, **kwds) має бути еквівалентним meth(*args, **kwds).

Цей прапорець дає змогу оптимізувати типові виклики методів, як-от obj.meth(): він уникає створення тимчасового об’єкта «зв’язаного методу» для obj.meth.

Added in version 3.8.

Наслідування:

This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For extension types, it is inherited whenever tp_descr_get is inherited.

Py_TPFLAGS_MANAGED_DICT

This bit indicates that instances of the class have a __dict__ attribute, and that the space for the dictionary is managed by the VM.

If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.

The type traverse function must call PyObject_VisitManagedDict() and its clear function must call PyObject_ClearManagedDict().

Added in version 3.12.

Наслідування:

This flag is inherited unless the tp_dictoffset field is set in a superclass.

Py_TPFLAGS_MANAGED_WEAKREF

This bit indicates that instances of the class should be weakly referenceable.

Added in version 3.12.

Наслідування:

This flag is inherited unless the tp_weaklistoffset field is set in a superclass.

Py_TPFLAGS_PREHEADER

These bits indicate that the VM will manage some fields by storing them before the object. Currently, this macro is equivalent to Py_TPFLAGS_MANAGED_DICT | Py_TPFLAGS_MANAGED_WEAKREF.

This macro value relies on the implementation of the VM, so its value is not stable and may change in a future version. Prefer using individual flags instead.

Added in version 3.12.

Py_TPFLAGS_ITEMS_AT_END

Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.

Indicates that the variable-sized portion of an instance of this type is at the end of the instance’s memory area, at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).

When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized. Python does not check this.

Added in version 3.12.

Наслідування:

This flag is inherited.

Py_TPFLAGS_LONG_SUBCLASS
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS

Ці позначки використовуються такими функціями, як PyLong_Check(), щоб швидко визначити, чи є тип підкласом вбудованого типу; такі спеціальні перевірки є швидшими, ніж загальні перевірки, наприклад PyObject_IsInstance(). Користувальницькі типи, які успадковуються від вбудованих, повинні мати належним чином встановлені tp_flags, інакше код, який взаємодіє з такими типами, поводитиметься по-різному залежно від типу перевірки, що використовується.

Py_TPFLAGS_HAVE_FINALIZE

Цей біт встановлюється, коли слот tp_finalize присутній у структурі типу.

Added in version 3.4.

Застаріло починаючи з версії 3.8: Цей прапорець більше не потрібен, оскільки інтерпретатор припускає, що слот tp_finalize завжди присутній у структурі типу.

Py_TPFLAGS_HAVE_VECTORCALL

Цей біт встановлюється, коли клас реалізує vectorcall протокол. Перегляньте tp_vectorcall_offset для деталей.

Наслідування:

This bit is inherited if tp_call is also inherited.

Added in version 3.9.

Змінено в версії 3.12: This flag is now removed from a class when the class’s __call__() method is reassigned.

This flag can now be inherited by mutable classes.

Py_TPFLAGS_IMMUTABLETYPE

Цей біт встановлено для об’єктів типу, які є незмінними: атрибути типу не можна ні встановити, ні видалити.

PyType_Ready() автоматично застосовує цей прапорець до статичних типів.

Наслідування:

Цей прапорець не успадковується.

Added in version 3.10.

Py_TPFLAGS_DISALLOW_INSTANTIATION

Заборонити створення екземплярів типу: установіть для tp_new значення NULL і не створюйте ключ __new__ у словнику типу.

Прапор має бути встановлений до створення типу, а не після. Наприклад, його потрібно встановити перед викликом PyType_Ready() для типу.

Прапорець автоматично встановлюється для статичних типів, якщо tp_base має значення NULL або &PyBaseObject_Type і tp_new має значення NULL.

Наслідування:

This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL tp_new (which is only possible via the C API).

Примітка

To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract base class), do not use this flag. Instead, make tp_new only succeed for subclasses.

Added in version 3.10.

Py_TPFLAGS_MAPPING

Цей біт вказує на те, що екземпляри класу можуть відповідати шаблонам відображення, якщо використовуються як суб’єкт блоку match. Він автоматично встановлюється під час реєстрації або підкласу collections.abc.Mapping і скасовується під час реєстрації collections.abc.Sequence.

Примітка

Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

Наслідування:

This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.

Дивись також

PEP 634 – Структурне зіставлення шаблонів: Специфікація

Added in version 3.10.

Py_TPFLAGS_SEQUENCE

Цей біт вказує на те, що екземпляри класу можуть відповідати шаблонам послідовності, коли використовуються як суб’єкт блоку match. Він автоматично встановлюється під час реєстрації або підкласу collections.abc.Sequence і скасовується під час реєстрації collections.abc.Mapping.

Примітка

Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

Наслідування:

This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.

Дивись також

PEP 634 – Структурне зіставлення шаблонів: Специфікація

Added in version 3.10.

Py_TPFLAGS_VALID_VERSION_TAG

Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()

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

This flag is present in header files, but is not be used. It will be removed in a future version of CPython

const char *PyTypeObject.tp_doc

An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the __doc__ attribute on the type and instances of the type.

Наслідування:

Це поле не успадковується підтипами.

traverseproc PyTypeObject.tp_traverse

An optional pointer to a traversal function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_traverse(PyObject *self, visitproc visit, void *arg);

Більше інформації про схему збирання сміття Python можна знайти в розділі Підтримка циклічного збирання сміття.

The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implementation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that are Python objects that the instance owns. For example, this is function local_traverse() from the _thread extension module:

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

Зауважте, що Py_VISIT() викликається лише для тих членів, які можуть брати участь у еталонних циклах. Хоча також є член self->key, він може бути лише NULL або рядком Python і тому не може бути частиною еталонного циклу.

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

Heap types (Py_TPFLAGS_HEAPTYPE) must visit their type with:

Py_VISIT(Py_TYPE(self));

It is only needed since Python 3.9. To support Python 3.8 and older, this line must be conditional:

#if PY_VERSION_HEX >= 0x03090000
    Py_VISIT(Py_TYPE(self));
#endif

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

PyObject_VisitManagedDict((PyObject*)self, visit, arg);

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

Під час реалізації tp_traverse необхідно відвідати лише члени, якими володіє примірник (через наявність сильних посилань на них). Наприклад, якщо об’єкт підтримує слабкі посилання через слот tp_weaklist, вказівник, що підтримує зв’язаний список (на що вказує tp_weaklist), не має відвідуватися, як це робить екземпляр не володіє безпосередньо слабкими посиланнями на себе (список слабких посилань існує для підтримки механізму слабких посилань, але екземпляр не має сильного посилання на елементи всередині нього, оскільки їх можна видалити, навіть якщо екземпляр все ще живий).

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

Екземпляри виділених у купі типів містять посилання на свій тип. Таким чином, їх функція обходу повинна або відвідати Py_TYPE(self), або делегувати цю відповідальність, викликавши tp_traverse іншого типу, виділеного купою (наприклад, суперкласу, виділеного купою). Якщо вони цього не роблять, об’єкт типу може не збиратися сміттям.

Примітка

The tp_traverse function can be called from any thread.

Змінено в версії 3.9: Очікується, що типи, виділені в купі, відвідуватимуть Py_TYPE(self) у tp_traverse. У попередніх версіях Python, через помилку 40217, це може призвести до збоїв у підкласах.

Наслідування:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

inquiry PyTypeObject.tp_clear

An optional pointer to a clear function. The signature is:

int tp_clear(PyObject *);

The purpose of this function is to break reference cycles that are causing a cyclic isolate so that the objects can be safely destroyed. A cleared object is a partially destroyed object; the object is not obligated to satisfy design invariants held during normal use.

tp_clear does not need to delete references to objects that can’t participate in reference cycles, such as Python strings or Python integers. However, it may be convenient to clear all references, and write the type’s tp_dealloc function to invoke tp_clear to avoid code duplication. (Beware that tp_clear might have already been called. Prefer calling idempotent functions like Py_CLEAR().)

Any non-trivial cleanup should be performed in tp_finalize instead of tp_clear.

Примітка

If tp_clear fails to break a reference cycle then the objects in the cyclic isolate may remain indefinitely uncollectable («leak»). See gc.garbage.

Примітка

Referents (direct and indirect) might have already been cleared; they are not guaranteed to be in a consistent state.

Примітка

The tp_clear function can be called from any thread.

Примітка

An object is not guaranteed to be automatically cleared before its destructor (tp_dealloc) is called.

This function differs from the destructor (tp_dealloc) in the following ways:

  • The purpose of clearing an object is to remove references to other objects that might participate in a reference cycle. The purpose of the destructor, on the other hand, is a superset: it must release all resources it owns, including references to objects that cannot participate in a reference cycle (e.g., integers) as well as the object’s own memory (by calling tp_free).

  • When tp_clear is called, other objects might still hold references to the object being cleared. Because of this, tp_clear must not deallocate the object’s own memory (tp_free). The destructor, on the other hand, is only called when no (strong) references exist, and as such, must safely destroy the object itself by deallocating it.

  • tp_clear might never be automatically called. An object’s destructor, on the other hand, will be automatically called some time after the object becomes unreachable (i.e., either there are no references to the object or the object is a member of a cyclic isolate).

No guarantees are made about when, if, or how often Python automatically clears an object, except:

  • Python will not automatically clear an object if it is reachable, i.e., there is a reference to it and it is not a member of a cyclic isolate.

  • Python will not automatically clear an object if it has not been automatically finalized (see tp_finalize). (If the finalizer resurrected the object, the object may or may not be automatically finalized again before it is cleared.)

  • If an object is a member of a cyclic isolate, Python will not automatically clear it if any member of the cyclic isolate has not yet been automatically finalized (tp_finalize).

  • Python will not destroy an object until after any automatic calls to its tp_clear function have returned. This ensures that the act of breaking a reference cycle does not invalidate the self pointer while tp_clear is still executing.

  • Python will not automatically call tp_clear multiple times concurrently.

CPython currently only automatically clears objects as needed to break reference cycles in a cyclic isolate, but future versions might clear objects regularly before their destruction.

Taken together, all tp_clear functions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not implement a tp_clear function, because it’s possible to prove that no reference cycle can be composed entirely of tuples. Therefore the tp_clear functions of other types are responsible for breaking any cycle containing a tuple. This isn’t immediately obvious, and there’s rarely a good reason to avoid implementing tp_clear.

Реалізації tp_clear мають видаляти посилання екземпляра на ті з його членів, які можуть бути об’єктами Python, і встановлювати його покажчики на ці члени на NULL, як у наступному прикладі:

static int
local_clear(PyObject *op)
{
    localobject *self = (localobject *) op;
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
}

The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL. This is because releasing the reference may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the contained object). If it’s possible for such code to reference self again, it’s important that the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR() macro performs the operations in a safe order.

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

PyObject_ClearManagedDict((PyObject*)self);

Більше інформації про схему збирання сміття Python можна знайти в розділі Підтримка циклічного збирання сміття.

Наслідування:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

Дивись також

Object Life Cycle for details about how this slot relates to other slots.

richcmpfunc PyTypeObject.tp_richcompare

Додатковий вказівник на функцію розширеного порівняння, сигнатура якої:

PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

Перший параметр гарантовано є екземпляром типу, визначеного PyTypeObject.

Функція має повертати результат порівняння (зазвичай Py_True або Py_False). Якщо порівняння не визначено, воно має повернути Py_NotImplemented, якщо сталася інша помилка, воно має повернути NULL і встановити умову винятку.

Наступні константи визначено для використання як третій аргумент для tp_richcompare і для PyObject_RichCompare():

Постійний

Порівняння

Py_LT

<

Py_LE

<=

Py_EQ

==

Py_NE

!=

Py_GT

>

Py_GE

>=

Наступний макрос визначено для полегшення написання розширених функцій порівняння:

Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)

Повертає з функції Py_True або Py_False, залежно від результату порівняння. VAL_A і VAL_B повинні бути впорядковані операторами порівняння C (наприклад, вони можуть бути C int або float). Третій аргумент визначає необхідну операцію, як для PyObject_RichCompare().

The returned value is a new strong reference.

У разі помилки встановлює виняток і повертає NULL із функції.

Added in version 3.7.

Наслідування:

Group: tp_hash, tp_richcompare

Це поле успадковується підтипами разом із tp_hash: підтип успадковує tp_richcompare і tp_hash, коли підтип tp_richcompare і tp_hash мають значення NULL.

За замовчуванням:

PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However, if only tp_hash is defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.

Py_ssize_t PyTypeObject.tp_weaklistoffset

While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all possible.

If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by PyObject_ClearWeakRefs() and the PyWeakref_* functions. The instance structure needs to include a field of type PyObject* which is initialized to NULL.

Не плутайте це поле з tp_weaklist; це заголовок списку для слабких посилань на сам об’єкт типу.

It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklistoffset.

Наслідування:

Це поле успадковується підтипами, але перегляньте наведені нижче правила. Підтип може замінити це зміщення; це означає, що підтип використовує інший слабкий заголовок списку посилань, ніж базовий тип. Оскільки заголовок списку завжди можна знайти через tp_weaklistoffset, це не повинно бути проблемою.

За замовчуванням:

If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_flags field, then tp_weaklistoffset will be set to a negative value, to indicate that it is unsafe to use this field.

getiterfunc PyTypeObject.tp_iter

Додатковий покажчик на функцію, яка повертає iterator для об’єкта. Його наявність зазвичай сигналізує про те, що екземпляри цього типу iterable (хоча послідовності можуть бути ітерованими без цієї функції).

Ця функція має той самий підпис, що й PyObject_GetIter():

PyObject *tp_iter(PyObject *self);

Наслідування:

Це поле успадковується підтипами.

iternextfunc PyTypeObject.tp_iternext

Додатковий покажчик на функцію, яка повертає наступний елемент у iterator. Підпис:

PyObject *tp_iternext(PyObject *self);

Коли ітератор вичерпано, він повинен повернути NULL; Виняток StopIteration може бути встановлений або не встановлений. Коли виникає інша помилка, вона також має повернути NULL. Його наявність сигналізує про те, що екземпляри цього типу є ітераторами.

Типи ітераторів також повинні визначати функцію tp_iter, і ця функція має повертати сам екземпляр ітератора (а не новий екземпляр ітератора).

Ця функція має той самий підпис, що й PyIter_Next().

Наслідування:

Це поле успадковується підтипами.

struct PyMethodDef *PyTypeObject.tp_methods

Необов’язковий вказівник на статичний масив структур PyMethodDef із закінченням NULL, що оголошує регулярні методи цього типу.

Для кожного запису в масиві до словника типу (див. tp_dict нижче) додається запис, що містить дескриптор методу.

Наслідування:

Це поле не успадковується підтипами (методи успадковуються через інший механізм).

struct PyMemberDef *PyTypeObject.tp_members

Необов’язковий вказівник на статичний масив структур PyMemberDef із закінченням NULL, що оголошує регулярні члени даних (поля або слоти) екземплярів цього типу.

Для кожного запису в масиві до словника типу (див. tp_dict нижче) додається запис, що містить дескриптор члена.

Наслідування:

Це поле не успадковується підтипами (члени успадковуються через інший механізм).

struct PyGetSetDef *PyTypeObject.tp_getset

Додатковий вказівник на статичний масив структур PyGetSetDef із закінченням NULL, що оголошує обчислені атрибути екземплярів цього типу.

Для кожного запису в масиві до словника типу (див. tp_dict нижче) додається запис, що містить дескриптор getset.

Наслідування:

Це поле не успадковується підтипами (обчислені атрибути успадковуються за допомогою іншого механізму).

PyTypeObject *PyTypeObject.tp_base

Додатковий покажчик на базовий тип, властивості якого успадковуються. На цьому рівні підтримується лише одиночне успадкування; множинне успадкування вимагає динамічного створення об’єкта типу шляхом виклику метатипу.

Примітка

Ініціалізація слота підпорядковується правилам ініціалізації глобалів. C99 вимагає, щоб ініціалізатори були «константами адреси». Позначення функцій, такі як PyType_GenericNew(), з неявним перетворенням на вказівник, є дійсними константами адрес C99.

However, the unary „&“ operator applied to a non-static variable like PyBaseObject_Type is not required to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly standard conforming in this particular behavior.

Отже, tp_base має бути встановлено у функції ініціалізації модуля розширення.

Наслідування:

Це поле не успадковується підтипами (очевидно).

За замовчуванням:

У цьому полі за замовчуванням встановлено &PyBaseObject_Type (що програмістам на Python відоме як тип object).

PyObject *PyTypeObject.tp_dict

Словник типу зберігається тут у PyType_Ready().

This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations (like __add__()). Once initialization for the type has finished, this field should be treated as read-only.

Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary for an arbitrary type.

Змінено в версії 3.12: Internals detail: For static builtin types, this is always NULL. Instead, the dict for such types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary type.

Наслідування:

Це поле не успадковується підтипами (хоча атрибути, визначені тут, успадковуються за допомогою іншого механізму).

За замовчуванням:

Якщо це поле має значення NULL, PyType_Ready() призначить йому новий словник.

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

Небезпечно використовувати PyDict_SetItem() або іншим чином змінювати tp_dict за допомогою словника C-API.

descrgetfunc PyTypeObject.tp_descr_get

Додатковий вказівник на функцію «отримання дескриптора».

Сигнатура функції:

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

Наслідування:

Це поле успадковується підтипами.

descrsetfunc PyTypeObject.tp_descr_set

Додатковий покажчик на функцію для встановлення та видалення значення дескриптора.

Сигнатура функції:

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

Аргумент value має значення NULL, щоб видалити значення.

Наслідування:

Це поле успадковується підтипами.

Py_ssize_t PyTypeObject.tp_dictoffset

While this field is still supported, Py_TPFLAGS_MANAGED_DICT should be used instead, if at all possible.

Якщо екземпляри цього типу мають словник, що містить змінні екземпляра, це поле ненульове та містить зміщення в екземплярах типу словника змінних екземплярів; це зміщення використовується PyObject_GenericGetAttr().

Не плутайте це поле з tp_dict; це словник для атрибутів самого об’єкта типу.

The value specifies the offset of the dictionary from the start of the instance structure.

The tp_dictoffset should be regarded as write-only. To get the pointer to the dictionary call PyObject_GenericGetDict(). Calling PyObject_GenericGetDict() may need to allocate memory for the dictionary, so it is may be more efficient to call PyObject_GetAttr() when accessing an attribute on the object.

It is an error to set both the Py_TPFLAGS_MANAGED_DICT bit and tp_dictoffset.

Наслідування:

This field is inherited by subtypes. A subtype should not override this offset; doing so could be unsafe, if C code tries to access the dictionary at the previous offset. To properly support inheritance, use Py_TPFLAGS_MANAGED_DICT.

За замовчуванням:

This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.

If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, then tp_dictoffset will be set to -1, to indicate that it is unsafe to use this field.

initproc PyTypeObject.tp_init

Додатковий покажчик на функцію ініціалізації екземпляра.

This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__() method again.

Сигнатура функції:

int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword arguments of the call to __init__().

Функція tp_init, якщо вона не NULL, викликається, коли екземпляр створюється звичайним викликом його типу, після функції tp_new типу. повернув екземпляр типу. Якщо функція tp_new повертає екземпляр якогось іншого типу, який не є підтипом вихідного типу, функція tp_init не викликається; якщо tp_new повертає екземпляр підтипу вихідного типу, викликається tp_init підтипу.

У разі успіху повертає 0, -1 і встановлює виняток у випадку помилки.

Наслідування:

Це поле успадковується підтипами.

За замовчуванням:

Для статичних типів це поле не має значення за замовчуванням.

allocfunc PyTypeObject.tp_alloc

Додатковий покажчик на функцію виділення екземпляра.

Сигнатура функції:

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

Наслідування:

Static subtypes inherit this slot, which will be PyType_GenericAlloc() if inherited from object.

Heap subtypes do not inherit this slot.

За замовчуванням:

For heap subtypes, this field is always set to PyType_GenericAlloc().

For static subtypes, this slot is inherited (see above).

newfunc PyTypeObject.tp_new

Додатковий покажчик на функцію створення екземпляра.

Сигнатура функції:

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

Аргумент subtype — це тип об’єкта, що створюється; аргументи args і kwds представляють позиційні та ключові аргументи виклику типу. Зауважте, що subtype не обов’язково дорівнює типу, чия функція tp_new викликається; це може бути підтип цього типу (але не непов’язаний тип).

Функція tp_new має викликати subtype->tp_alloc(subtype, nitems), щоб виділити простір для об’єкта, а потім виконувати подальшу ініціалізацію лише стільки, скільки це абсолютно необхідно. Ініціалізацію, яку можна безпечно проігнорувати або повторити, слід розмістити в обробнику tp_init. Хорошим емпіричним правилом є те, що для незмінних типів уся ініціалізація має відбуватися в tp_new, тоді як для змінних типів більшість ініціалізацій має бути відкладено до tp_init.

Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in Python.

Наслідування:

Це поле успадковується підтипами, за винятком статичних типів, у яких tp_base має значення NULL або &PyBaseObject_Type.

За замовчуванням:

Для статичних типів це поле не має типового значення. Це означає, що якщо слот визначено як NULL, тип не можна викликати для створення нових екземплярів; мабуть, існує якийсь інший спосіб створення екземплярів, як-от фабрична функція.

freefunc PyTypeObject.tp_free

Додатковий покажчик на функцію звільнення екземпляра. Його підпис:

void tp_free(void *self);

This function must free the memory allocated by tp_alloc.

Наслідування:

Static subtypes inherit this slot, which will be PyObject_Free() if inherited from object. Exception: If the type supports garbage collection (i.e., the Py_TPFLAGS_HAVE_GC flag is set in tp_flags) and it would inherit PyObject_Free(), then this slot is not inherited but instead defaults to PyObject_GC_Del().

Heap subtypes do not inherit this slot.

За замовчуванням:

For heap subtypes, this slot defaults to a deallocator suitable to match PyType_GenericAlloc() and the value of the Py_TPFLAGS_HAVE_GC flag.

For static subtypes, this slot is inherited (see above).

inquiry PyTypeObject.tp_is_gc

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

The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object’s type’s tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a non-collectible instance. The signature is:

int tp_is_gc(PyObject *self);

(Єдиним прикладом цього є самі типи. Метатип PyType_Type визначає цю функцію, щоб розрізняти статично та динамічно виділені типи.)

Наслідування:

Це поле успадковується підтипами.

За замовчуванням:

This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.

PyObject *PyTypeObject.tp_bases

Кортеж базових типів.

This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.

For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of PyType_FromSpecWithBases(). The argument form is preferred.

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

Multiple inheritance does not work well for statically defined types. If you set tp_bases to a tuple, Python will not raise an error, but some slots will only be inherited from the first base.

Наслідування:

Це поле не успадковується.

PyObject *PyTypeObject.tp_mro

Кортеж, що містить розширений набір базових типів, починаючи з самого типу та закінчуючи object, у порядку вирішення методів.

This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.

Наслідування:

Це поле не успадковується; він обчислюється за допомогою PyType_Ready().

PyObject *PyTypeObject.tp_cache

Невикористаний. Тільки для внутрішнього використання.

Наслідування:

Це поле не успадковується.

void *PyTypeObject.tp_subclasses

A collection of subclasses. Internal use only. May be an invalid pointer.

To get a list of subclasses, call the Python method __subclasses__().

Змінено в версії 3.12: For some types, this field does not hold a valid PyObject*. The type was changed to void* to indicate this.

Наслідування:

Це поле не успадковується.

PyObject *PyTypeObject.tp_weaklist

Голова списку слабких посилань для слабких посилань на об’єкт цього типу. Не передається у спадок. Тільки для внутрішнього використання.

Змінено в версії 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs are added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the internal _PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.

Наслідування:

Це поле не успадковується.

destructor PyTypeObject.tp_del

Це поле застаріло. Натомість використовуйте tp_finalize.

unsigned int PyTypeObject.tp_version_tag

Використовується для індексування в кеш методів. Тільки для внутрішнього використання.

Наслідування:

Це поле не успадковується.

destructor PyTypeObject.tp_finalize

An optional pointer to an instance finalization function. This is the C implementation of the __del__() special method. Its signature is:

void tp_finalize(PyObject *self);

The primary purpose of finalization is to perform any non-trivial cleanup that must be performed before the object is destroyed, while the object and any other objects it directly or indirectly references are still in a consistent state. The finalizer is allowed to execute arbitrary Python code.

Before Python automatically finalizes an object, some of the object’s direct or indirect referents might have themselves been automatically finalized. However, none of the referents will have been automatically cleared (tp_clear) yet.

Other non-finalized objects might still be using a finalized object, so the finalizer must leave the object in a sane state (e.g., invariants are still met).

Примітка

After Python automatically finalizes an object, Python might start automatically clearing (tp_clear) the object and its referents (direct and indirect). Cleared objects are not guaranteed to be in a consistent state; a finalized object must be able to tolerate cleared referents.

Примітка

An object is not guaranteed to be automatically finalized before its destructor (tp_dealloc) is called. It is recommended to call PyObject_CallFinalizerFromDealloc() at the beginning of tp_dealloc to guarantee that the object is always finalized before destruction.

Примітка

The tp_finalize function can be called from any thread, although the GIL will be held.

Примітка

The tp_finalize function can be called during shutdown, after some global variables have been deleted. See the documentation of the __del__() method for details.

When Python finalizes an object, it behaves like the following algorithm:

  1. Python might mark the object as finalized. Currently, Python always marks objects whose type supports garbage collection (i.e., the Py_TPFLAGS_HAVE_GC flag is set in tp_flags) and never marks other types of objects; this might change in a future version.

  2. If the object is not marked as finalized and its tp_finalize finalizer function is non-NULL, the finalizer function is called.

  3. If the finalizer function was called and the finalizer made the object reachable (i.e., there is a reference to the object and it is not a member of a cyclic isolate), then the finalizer is said to have resurrected the object. It is unspecified whether the finalizer can also resurrect the object by adding a new reference to the object that does not make it reachable, i.e., the object is (still) a member of a cyclic isolate.

  4. If the finalizer resurrected the object, the object’s pending destruction is canceled and the object’s finalized mark might be removed if present. Currently, Python never removes the finalized mark; this might change in a future version.

Automatic finalization refers to any finalization performed by Python except via calls to PyObject_CallFinalizer() or PyObject_CallFinalizerFromDealloc(). No guarantees are made about when, if, or how often an object is automatically finalized, except:

  • Python will not automatically finalize an object if it is reachable, i.e., there is a reference to it and it is not a member of a cyclic isolate.

  • Python will not automatically finalize an object if finalizing it would not mark the object as finalized. Currently, this applies to objects whose type does not support garbage collection, i.e., the Py_TPFLAGS_HAVE_GC flag is not set. Such objects can still be manually finalized by calling PyObject_CallFinalizer() or PyObject_CallFinalizerFromDealloc().

  • Python will not automatically finalize any two members of a cyclic isolate concurrently.

  • Python will not automatically finalize an object after it has automatically cleared (tp_clear) the object.

  • If an object is a member of a cyclic isolate, Python will not automatically finalize it after automatically clearing (see tp_clear) any other member.

  • Python will automatically finalize every member of a cyclic isolate before it automatically clears (see tp_clear) any of them.

  • If Python is going to automatically clear an object (tp_clear), it will automatically finalize the object first.

Python currently only automatically finalizes objects that are members of a cyclic isolate, but future versions might finalize objects regularly before their destruction.

To manually finalize an object, do not call this function directly; call PyObject_CallFinalizer() or PyObject_CallFinalizerFromDealloc() instead.

tp_finalize should leave the current exception status unchanged. The recommended way to write a non-trivial finalizer is to back up the exception at the beginning by calling PyErr_GetRaisedException() and restore the exception at the end by calling PyErr_SetRaisedException(). If an exception is encountered in the middle of the finalizer, log and clear it with PyErr_WriteUnraisable() or PyErr_FormatUnraisable(). For example:

static void
foo_finalize(PyObject *self)
{
    // Save the current exception, if any.
    PyObject *exc = PyErr_GetRaisedException();

    // ...

    if (do_something_that_might_raise() != success_indicator) {
        PyErr_WriteUnraisable(self);
        goto done;
    }

done:
    // Restore the saved exception.  This silently discards any exception
    // raised above, so be sure to call PyErr_WriteUnraisable first if
    // necessary.
    PyErr_SetRaisedException(exc);
}

Наслідування:

Це поле успадковується підтипами.

Added in version 3.4.

Змінено в версії 3.8: Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE flags bit in order for this field to be used. This is no longer required.

Дивись також

vectorcallfunc PyTypeObject.tp_vectorcall

A vectorcall function to use for calls of this type object (rather than instances). In other words, tp_vectorcall can be used to optimize type.__call__, which typically returns a new instance of type.

As with any vectorcall function, if tp_vectorcall is NULL, the tp_call protocol (Py_TYPE(type)->tp_call) is used instead.

Примітка

The vectorcall protocol requires that the vectorcall function has the same behavior as the corresponding tp_call. This means that type->tp_vectorcall must match the behavior of Py_TYPE(type)->tp_call.

Specifically, if type uses the default metaclass, type->tp_vectorcall must behave the same as PyType_Type->tp_call, which:

  • calls type->tp_new,

  • if the result is a subclass of type, calls type->tp_init on the result of tp_new, and

  • returns the result of tp_new.

Typically, tp_vectorcall is overridden to optimize this process for specific tp_new and tp_init. When doing this for user-subclassable types, note that both can be overridden (using __new__() and __init__(), respectively).

Наслідування:

Це поле ніколи не успадковується.

Added in version 3.9: (поле існує з 3.8, але використовується лише з 3.9)

unsigned char PyTypeObject.tp_watched

Internal. Do not use.

Added in version 3.12.

Статичні типи

Традиційно типи, визначені в коді C, є статичними, тобто статична структура PyTypeObject визначається безпосередньо в коді та ініціалізується за допомогою PyType_Ready().

Це призводить до типів, які обмежені відносно типів, визначених у Python:

  • Статичні типи обмежені однією базою, тобто вони не можуть використовувати множинне успадкування.

  • Об’єкти статичного типу (але не обов’язково їх екземпляри) незмінні. Неможливо додати або змінити атрибути об’єкта типу з Python.

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

Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static types must be compiled for a specific Python minor version.

Типи купи

An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.

This is done by filling a PyType_Spec structure and calling PyType_FromSpec(), PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or PyType_FromMetaclass().

Числові об’єктні структури

type PyNumberMethods

Ця структура містить покажчики на функції, які об’єкт використовує для реалізації протоколу чисел. Кожна функція використовується функцією з подібною назвою, задокументованою в розділі Номер протоколу.

Ось визначення структури:

typedef struct {
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

Примітка

Двійкові та потрійні функції повинні перевіряти тип усіх своїх операндів і здійснювати необхідні перетворення (принаймні один із операндів є екземпляром визначеного типу). Якщо операція не визначена для заданих операндів, двійкові та тернарні функції повинні повернути Py_NotImplemented, якщо сталася інша помилка, вони повинні повернути NULL і встановити виняток.

Примітка

The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed in Python 3.0.1.

binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

Відображення структур об’єктів

type PyMappingMethods

Ця структура містить покажчики на функції, які об’єкт використовує для реалізації протоколу відображення. Він складається з трьох членів:

lenfunc PyMappingMethods.mp_length

Ця функція використовується PyMapping_Size() і PyObject_Size() і має однакову сигнатуру. Цей слот може бути встановлений на NULL, якщо об’єкт не має визначеної довжини.

binaryfunc PyMappingMethods.mp_subscript

Ця функція використовується PyObject_GetItem() і PySequence_GetSlice(), і має такий же підпис, як PyObject_GetItem(). Цей слот має бути заповнений, щоб функція PyMapping_Check() повернула 1, інакше вона може бути NULL.

objobjargproc PyMappingMethods.mp_ass_subscript

This function is used by PyObject_SetItem(), PyObject_DelItem(), PySequence_SetSlice() and PySequence_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.

Структури об’єктів послідовності

type PySequenceMethods

Ця структура містить покажчики на функції, які об’єкт використовує для реалізації протоколу послідовності.

lenfunc PySequenceMethods.sq_length

Ця функція використовується PySequence_Size() і PyObject_Size() і має однакову сигнатуру. Він також використовується для обробки негативних індексів через слоти sq_item і sq_ass_item.

binaryfunc PySequenceMethods.sq_concat

Ця функція використовується PySequence_Concat() і має такий самий підпис. Він також використовується оператором + після спроби додавання чисел через слот nb_add.

ssizeargfunc PySequenceMethods.sq_repeat

Ця функція використовується PySequence_Repeat() і має такий самий підпис. Він також використовується оператором * після спроби числового множення через слот nb_multiply.

ssizeargfunc PySequenceMethods.sq_item

Ця функція використовується PySequence_GetItem() і має такий самий підпис. Він також використовується PyObject_GetItem() після спроби підписки через слот mp_subscript. Цей слот має бути заповнений, щоб функція PySequence_Check() повертала 1, інакше вона може бути NULL.

Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is to the function.

ssizeobjargproc PySequenceMethods.sq_ass_item

Ця функція використовується PySequence_SetItem() і має такий самий підпис. Він також використовується PyObject_SetItem() і PyObject_DelItem() після спроби призначення та видалення елемента через слот mp_ass_subscript. Цей слот можна залишити NULL, якщо об’єкт не підтримує призначення та видалення елементів.

objobjproc PySequenceMethods.sq_contains

Ця функція може використовуватися PySequence_Contains() і має такий самий підпис. Цей слот можна залишити NULL, у цьому випадку PySequence_Contains() просто обходить послідовність, поки не знайде збіг.

binaryfunc PySequenceMethods.sq_inplace_concat

Ця функція використовується PySequence_InPlaceConcat() і має такий самий підпис. Він повинен змінити свій перший операнд і повернути його. Цей слот можна залишити NULL, у цьому випадку PySequence_InPlaceConcat() повернеться до PySequence_Concat(). Він також використовується розширеним призначенням += після спроби додавання чисел на місці через слот nb_inplace_add.

ssizeargfunc PySequenceMethods.sq_inplace_repeat

Ця функція використовується PySequence_InPlaceRepeat() і має такий самий підпис. Він повинен змінити свій перший операнд і повернути його. Цей слот можна залишити NULL, у цьому випадку PySequence_InPlaceRepeat() повернеться до PySequence_Repeat(). Він також використовується розширеним призначенням *= після спроби числового множення на місці через слот nb_inplace_multiply.

Буферні об’єктні структури

type PyBufferProcs

Ця структура містить покажчики на функції, необхідні для протоколу буфера. Протокол визначає, як об’єкт-експортер може надавати свої внутрішні дані об’єктам-споживачам.

getbufferproc PyBufferProcs.bf_getbuffer

Сигнатура цієї функції:

int (PyObject *exporter, Py_buffer *view, int flags);

Обробляти запит до exporter для заповнення view, як зазначено flags. За винятком пункту (3), реалізація цієї функції ПОВИННА виконувати такі дії:

  1. Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.

  2. Заповніть необхідні поля.

  3. Збільшити внутрішній лічильник для кількості експортів.

  4. Set view->obj to exporter and increment view->obj.

  5. Повернути 0.

Якщо експортер є частиною ланцюжка або дерева постачальників буферів, можна використовувати дві основні схеми:

  • Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference to itself.

  • Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new reference to the root object.

Окремі поля view описані в розділі Структура буфера, правила, як експортер повинен реагувати на конкретні запити, знаходяться в розділі Типи запитів буфера.

Уся пам’ять, на яку вказує структура Py_buffer, належить експортеру та має залишатися чинною, доки не залишиться споживачів. format, shape, strides, suboffsets та internal доступні лише для читання для споживача.

PyBuffer_FillInfo() забезпечує простий спосіб відкрити простий буфер байтів, правильно обробляючи всі типи запитів.

PyObject_GetBuffer() — це інтерфейс для споживача, який обертає цю функцію.

releasebufferproc PyBufferProcs.bf_releasebuffer

Сигнатура цієї функції:

void (PyObject *exporter, Py_buffer *view);

Обробляти запит на звільнення ресурсів буфера. Якщо не потрібно звільняти ресурси, PyBufferProcs.bf_releasebuffer може мати значення NULL. В іншому випадку стандартна реалізація цієї функції виконає наступні додаткові дії:

  1. Зменшити внутрішній лічильник для кількості експортів.

  2. Якщо лічильник 0, звільнити всю пам’ять, пов’язану з view.

Експортер ПОВИНЕН використовувати поле internal, щоб відстежувати ресурси, пов’язані з буфером. Це поле гарантовано залишається постійним, тоді як споживач МОЖЕ передати копію вихідного буфера як аргумент view.

This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release() (this scheme is useful for breaking reference cycles).

PyBuffer_Release() — це інтерфейс для споживача, який обертає цю функцію.

Асинхронні об’єктні структури

Added in version 3.5.

type PyAsyncMethods

Ця структура містить покажчики на функції, необхідні для реалізації об’єктів awaitable і asynchronous iterator.

Ось визначення структури:

typedef struct {
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
    sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await

Сигнатура цієї функції:

PyObject *am_await(PyObject *self);

Повернений об’єкт має бути iterator, тобто PyIter_Check() має повернути для нього 1.

Цей слот може мати значення NULL, якщо об’єкт не є awaitable.

unaryfunc PyAsyncMethods.am_aiter

Сигнатура цієї функції:

PyObject *am_aiter(PyObject *self);

Must return an asynchronous iterator object. See __anext__() for details.

Цей слот може мати значення NULL, якщо об’єкт не реалізує протокол асинхронної ітерації.

unaryfunc PyAsyncMethods.am_anext

Сигнатура цієї функції:

PyObject *am_anext(PyObject *self);

Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.

sendfunc PyAsyncMethods.am_send

Сигнатура цієї функції:

PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);

Дивіться PyIter_Send() для деталей. Цей слот може мати значення NULL.

Added in version 3.10.

Типи слотів

typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
Part of the Stable ABI.

The purpose of this function is to separate memory allocation from memory initialization. It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If the type’s tp_itemsize is non-zero, the object’s ob_size field should be initialized to nitems and the length of the allocated memory block should be tp_basicsize + nitems*tp_itemsize, rounded up to a multiple of sizeof(void*); otherwise, nitems is not used and the length of the block should be tp_basicsize.

Ця функція не повинна виконувати будь-яку іншу ініціалізацію екземпляра, навіть не для виділення додаткової пам’яті; це має зробити tp_new.

typedef void (*destructor)(PyObject*)
Part of the Stable ABI.
typedef void (*freefunc)(void*)

Перегляньте tp_free.

typedef PyObject *(*newfunc)(PyTypeObject*, PyObject*, PyObject*)
Part of the Stable ABI.

Перегляньте tp_new.

typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

Перегляньте tp_init.

typedef PyObject *(*reprfunc)(PyObject*)
Part of the Stable ABI.

Перегляньте tp_repr.

typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Part of the Stable ABI.

Повертає значення названого атрибута для об’єкта.

typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Part of the Stable ABI.

Установіть для об’єкта значення іменованого атрибута. Аргумент значення має значення NULL, щоб видалити атрибут.

typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
Part of the Stable ABI.

Повертає значення названого атрибута для об’єкта.

Перегляньте tp_getattro.

typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
Part of the Stable ABI.

Установіть для об’єкта значення іменованого атрибута. Аргумент значення має значення NULL, щоб видалити атрибут.

Перегляньте tp_setattro.

typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

See tp_descr_get.

typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

See tp_descr_set.

typedef Py_hash_t (*hashfunc)(PyObject*)
Part of the Stable ABI.

Перегляньте tp_hash.

typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Part of the Stable ABI.

Перегляньте tp_richcompare.

typedef PyObject *(*getiterfunc)(PyObject*)
Part of the Stable ABI.

Перегляньте tp_iter.

typedef PyObject *(*iternextfunc)(PyObject*)
Part of the Stable ABI.

Перегляньте tp_iternext.

typedef Py_ssize_t (*lenfunc)(PyObject*)
Part of the Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
Part of the Stable ABI since version 3.12.
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
Part of the Stable ABI since version 3.12.
typedef PyObject *(*unaryfunc)(PyObject*)
Part of the Stable ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)

Перегляньте am_send.

typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
Part of the Stable ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
Part of the Stable ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

Приклади

Нижче наведено прості приклади визначень типів Python. Вони включають загальне використання, з яким ви можете зіткнутися. Деякі демонструють хитрі кутові випадки. Більше прикладів, практичної інформації та підручника див. Визначення типів розширень: підручник і Визначення типів розширень: різні теми.

Базовий статичний тип:

typedef struct {
    PyObject_HEAD
    const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_new = myobj_new,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
};

Ви також можете знайти старіший код (особливо в кодовій базі CPython) із більш детальним ініціалізатором:

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "mymod.MyObject",               /* tp_name */
    sizeof(MyObject),               /* tp_basicsize */
    0,                              /* tp_itemsize */
    (destructor)myobj_dealloc,      /* tp_dealloc */
    0,                              /* tp_vectorcall_offset */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)myobj_repr,           /* tp_repr */
    0,                              /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    0,                              /* tp_hash */
    0,                              /* tp_call */
    0,                              /* tp_str */
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    0,                              /* tp_flags */
    PyDoc_STR("My objects"),        /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    0,                              /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    myobj_new,                      /* tp_new */
};

Тип, який підтримує слабкі посилання, екземпляри dicts і хешування:

typedef struct {
    PyObject_HEAD
    const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
         Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
         Py_TPFLAGS_MANAGED_WEAKREF,
    .tp_new = myobj_new,
    .tp_traverse = (traverseproc)myobj_traverse,
    .tp_clear = (inquiry)myobj_clear,
    .tp_alloc = PyType_GenericNew,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
    .tp_hash = (hashfunc)myobj_hash,
    .tp_richcompare = PyBaseObject_Type.tp_richcompare,
};

A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func) using Py_TPFLAGS_DISALLOW_INSTANTIATION flag:

typedef struct {
    PyUnicodeObject raw;
    char *extra;
} MyStr;

static PyTypeObject MyStr_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyStr",
    .tp_basicsize = sizeof(MyStr),
    .tp_base = NULL,  // set to &PyUnicode_Type in module init
    .tp_doc = PyDoc_STR("my custom str"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    .tp_repr = (reprfunc)myobj_repr,
};

Найпростіший статичний тип з екземплярами фіксованої довжини:

typedef struct {
    PyObject_HEAD
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
};

Найпростіший статичний тип з екземплярами змінної довжини:

typedef struct {
    PyObject_VAR_HEAD
    const char *data[1];
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject) - sizeof(char *),
    .tp_itemsize = sizeof(char *),
};