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> |
const char * |
__name__ |
X |
X |
||
X |
X |
X |
||||
X |
X |
|||||
X |
X |
X |
||||
X |
X |
|||||
__getattribute__, __getattr__ |
Г |
|||||
__setattr__, __delattr__ |
Г |
|||||
% |
||||||
__repr__ |
X |
X |
X |
|||
% |
||||||
% |
||||||
% |
||||||
__hash__ |
X |
Г |
||||
__call__ |
X |
X |
||||
__str__ |
X |
X |
||||
__getattribute__, __getattr__ |
X |
X |
Г |
|||
__setattr__, __delattr__ |
X |
X |
Г |
|||
% |
||||||
беззнаковий long |
X |
X |
? |
|||
const char * |
__doc__ |
X |
X |
|||
X |
Г |
|||||
X |
Г |
|||||
__lt__, __le__, __eq__, __ne__, __gt__, __ge__ |
X |
Г |
||||
X |
? |
|||||
__iter__ |
X |
|||||
__next__ |
X |
|||||
|
X |
X |
||||
|
X |
|||||
|
X |
X |
||||
__base__ |
X |
|||||
|
__dict__ |
? |
||||
__get__ |
X |
|||||
__set__, __delete__ |
X |
|||||
X |
? |
|||||
__init__ |
X |
X |
X |
|||
X |
? |
? |
||||
__new__ |
X |
X |
? |
? |
||
X |
X |
? |
? |
|||
X |
X |
|||||
< |
|
__bases__ |
~ |
|||
< |
|
__mro__ |
~ |
|||
[ |
|
|||||
порожній * |
__subclasses__ |
|||||
|
||||||
( |
||||||
беззнаковий int |
||||||
__del__ |
X |
|||||
беззнаковий символ |
||||||
підслоти¶
Слот |
спеціальні методи |
|
|---|---|---|
__await__ |
||
__aiter__ |
||
__anext__ |
||
__add__ __radd__ |
||
__iadd__ |
||
__sub__ __rsub__ |
||
__isub__ |
||
__mul__ __rmul__ |
||
__imul__ |
||
__mod__ __rmod__ |
||
__imod__ |
||
__divmod__ __rdivmod__ |
||
__pow__ __rpow__ |
||
__ipow__ |
||
__neg__ |
||
__pos__ |
||
__abs__ |
||
__bool__ |
||
__invert__ |
||
__lshift__ __rlshift__ |
||
__ilshift__ |
||
__rshift__ __rrshift__ |
||
__irshift__ |
||
__and__ __rand__ |
||
__iand__ |
||
__xor__ __rxor__ |
||
__ixor__ |
||
__or__ __ror__ |
||
__ior__ |
||
__int__ |
||
порожній * |
||
__float__ |
||
__floordiv__ |
||
__ifloordiv__ |
||
__truediv__ |
||
__itruediv__ |
||
__index__ |
||
__matmul__ __rmatmul__ |
||
__imatmul__ |
||
__len__ |
||
__getitem__ |
||
__setitem__, __delitem__ |
||
__len__ |
||
__add__ |
||
__mul__ |
||
__getitem__ |
||
__setitem__ __delitem__ |
||
__contains__ |
||
__iadd__ |
||
__imul__ |
||
__buffer__ |
||
__release_buffer__ |
||
типи слотів¶
typedef |
Типи параметрів |
Тип повернення |
|---|---|---|
|
||
|
пустий |
|
порожній * |
пустий |
|
int |
||
|
||
int |
||
|
|
|
PyObject *const char *
|
|
|
int |
||
|
||
int |
||
|
||
int |
||
|
Py_hash_t |
|
|
||
|
|
|
|
|
|
|
||
int |
||
пустий |
||
|
int |
|
PyObject * |
|
|
|
||
|
||
|
||
int |
||
int |
||
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.
The type object’s reference count is initialized to
1by thePyObject_HEAD_INITmacro. Note that for statically allocated type objects, the type’s instances (objects whoseob_typepoints back to the type) do not count as references. But for dynamically allocated type objects, the instances do count as references.Наслідування:
Це поле не успадковується підтипами.
Це тип типу, іншими словами його метатип. Він ініціалізується аргументом макросу
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 ifob_typeisNULL, and if so, initializes it to theob_typefield of the base class.PyType_Ready()will not change this field if it is non-zero.Наслідування:
Це поле успадковується підтипами.
Слоти PyVarObject¶
Для статично виділених об’єктів типу, це має бути ініціалізовано нулем. Для динамічно виділених об’єктів типу це поле має особливе внутрішнє значення.
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
Tdefined in moduleMin subpackageQin packagePshould have thetp_nameinitializer"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_namefield 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_itemsizefield, types with variable-length instances have a non-zerotp_itemsizefield. For a type with fixed-length instances, all instances have the same size, given intp_basicsize. (Exceptions to this rule can be made usingPyUnstable_Object_GC_NewWithExtraData().)For a type with variable-length instances, the instances must have an
ob_sizefield, and the instance size istp_basicsizeplus N timestp_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’sob_sizefield. Note that theob_sizefield may later be used for other purposes. For example,intinstances use the bits ofob_sizein an implementation-defined way; the underlying storage and its size should be accessed usingPyLong_Export().Примітка
The
ob_sizefield should be accessed using thePy_SIZE()andPy_SET_SIZE()macros.Also, the presence of an
ob_sizefield in the instance layout doesn’t mean that the instance structure is variable-length. For example, thelisttype has fixed-length instances, yet those instances have aob_sizefield. (As withint, avoid reading lists“ob_sizedirectly. CallPyList_Size()instead.)The
tp_basicsizeincludes size needed for data of the type’stp_base, plus any extra data needed by each instance.The correct way to set
tp_basicsizeis to use thesizeofoperator 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_basicsizemust be greater than or equal to the base’stp_basicsize.Since every type is a subtype of
object, this struct must includePyObjectorPyVarObject(depending on whetherob_sizeshould be included). These are usually defined by the macroPyObject_HEADorPyObject_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.basicsizeandPyType_FromMetaclass().Notes about alignment:
tp_basicsizemust be a multiple of_Alignof(PyObject). When usingsizeofon astructthat includesPyObject_HEAD, as recommended, the compiler ensures this. When not using a Cstruct, or when using compiler extensions like__attribute__((packed)), it is up to you.If the variable items require a particular alignment,
tp_basicsizeandtp_itemsizemust each be a multiple of that alignment. For example, if a type’s variable part stores adouble, 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 settp_itemsizeto 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’stp_freefunction to free the object itself.If you may call functions that may set the error indicator, you must use
PyErr_GetRaisedException()andPyErr_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 oftp_deallocto guarantee that the object is always finalized before destruction.If the type supports garbage collection (the
Py_TPFLAGS_HAVE_GCflag is set), the destructor should callPyObject_GC_UnTrack()before clearing any member fields.It is permissible to call
tp_clearfromtp_deallocto reduce code duplication and to guarantee that the object is always cleared before destruction. Beware thattp_clearmight have already been called.If the type is heap allocated (
Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned reference to its type object (viaPy_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_deallocmust 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 withPyErr_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_deallocmay 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 whichtp_deallocis 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 calledtp_deallocwill 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_VECTORCALLis set. If so, this must be a positive integer containing the offset in the instance of avectorcallfuncpointer.The vectorcallfunc pointer may be
NULL, in which case the instance behaves as ifPy_TPFLAGS_HAVE_VECTORCALLwas not set: calling the instance falls back totp_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 thePy_TPFLAGS_HAVE_VECTORCALLflag.Наслідування:
This field is always inherited. However, the
Py_TPFLAGS_HAVE_VECTORCALLflag is not always inherited. If it’s not set, then the subclass won’t use vectorcall, except whenPyVectorcall_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_richcompareis not set), an attempt to take the hash of the object raisesTypeError. This is the same as setting it toPyObject_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.За замовчуванням:
-
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.За замовчуванням:
-
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.За замовчуванням:
-
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_GCflag bit is inherited together with thetp_traverseandtp_clearfields, i.e. if thePy_TPFLAGS_HAVE_GCflag bit is clear in the subtype and thetp_traverseandtp_clearfields in the subtype exist and haveNULLvalues.За замовчуванням:
PyBaseObject_TypeusesPy_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, theob_typefield 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 usingPyObject_GC_NeworPyType_GenericAlloc()and deallocated (seetp_free) usingPyObject_GC_Del(). More information in section Підтримка циклічного збирання сміття.Наслідування:
Group:
Py_TPFLAGS_HAVE_GC,tp_traverse,tp_clearThe
Py_TPFLAGS_HAVE_GCflag bit is inherited together with thetp_traverseandtp_clearfields, i.e. if thePy_TPFLAGS_HAVE_GCflag bit is clear in the subtype and thetp_traverseandtp_clearfields in the subtype exist and haveNULLvalues.
-
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_IMMUTABLETYPEflag set. For extension types, it is inherited whenevertp_descr_getis 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_GCshould also be set.The type traverse function must call
PyObject_VisitManagedDict()and its clear function must callPyObject_ClearManagedDict().Added in version 3.12.
Наслідування:
This flag is inherited unless the
tp_dictoffsetfield 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_weaklistoffsetfield is set in a superclass.
-
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_callis 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_newonly succeed for subclasses.Added in version 3.10.
-
Py_TPFLAGS_MAPPING¶
Цей біт вказує на те, що екземпляри класу можуть відповідати шаблонам відображення, якщо використовуються як суб’єкт блоку
match. Він автоматично встановлюється під час реєстрації або підкласуcollections.abc.Mappingі скасовується під час реєстраціїcollections.abc.Sequence.Примітка
Py_TPFLAGS_MAPPINGandPy_TPFLAGS_SEQUENCEare 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_MAPPINGandPy_TPFLAGS_SEQUENCEare 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
-
Py_TPFLAGS_HEAPTYPE¶
-
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_GCflag bit is set. The signature is:int tp_traverse(PyObject *self, visitproc visit, void *arg);
Більше інформації про схему збирання сміття Python можна знайти в розділі Підтримка циклічного збирання сміття.
The
tp_traversepointer is used by the garbage collector to detect reference cycles. A typical implementation of atp_traversefunction simply callsPy_VISIT()on each of the instance’s members that are Python objects that the instance owns. For example, this is functionlocal_traverse()from the_threadextension 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_DICTbit is set in thetp_flagsfield, the traverse function must callPyObject_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 tolocal_traverse()to have these specific names; don’t name them just anything.Екземпляри виділених у купі типів містять посилання на свій тип. Таким чином, їх функція обходу повинна або відвідати
Py_TYPE(self), або делегувати цю відповідальність, викликавшиtp_traverseіншого типу, виділеного купою (наприклад, суперкласу, виділеного купою). Якщо вони цього не роблять, об’єкт типу може не збиратися сміттям.Примітка
The
tp_traversefunction can be called from any thread.Змінено в версії 3.9: Очікується, що типи, виділені в купі, відвідуватимуть
Py_TYPE(self)уtp_traverse. У попередніх версіях Python, через помилку 40217, це може призвести до збоїв у підкласах.Наслідування:
Group:
Py_TPFLAGS_HAVE_GC,tp_traverse,tp_clearThis field is inherited by subtypes together with
tp_clearand thePy_TPFLAGS_HAVE_GCflag bit: the flag bit,tp_traverse, andtp_clearare 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_cleardoes 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’stp_deallocfunction to invoketp_clearto avoid code duplication. (Beware thattp_clearmight have already been called. Prefer calling idempotent functions likePy_CLEAR().)Any non-trivial cleanup should be performed in
tp_finalizeinstead oftp_clear.Примітка
If
tp_clearfails to break a reference cycle then the objects in the cyclic isolate may remain indefinitely uncollectable («leak»). Seegc.garbage.Примітка
Referents (direct and indirect) might have already been cleared; they are not guaranteed to be in a consistent state.
Примітка
The
tp_clearfunction 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_clearis called, other objects might still hold references to the object being cleared. Because of this,tp_clearmust 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_clearmight 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_clearfunction have returned. This ensures that the act of breaking a reference cycle does not invalidate theselfpointer whiletp_clearis still executing.Python will not automatically call
tp_clearmultiple 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_clearfunctions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply atp_clearfunction. For example, the tuple type does not implement atp_clearfunction, because it’s possible to prove that no reference cycle can be composed entirely of tuples. Therefore thetp_clearfunctions 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 implementingtp_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 (viaPy_DECREF()) until after the pointer to the contained object is set toNULL. 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 beNULLat that time, so that self knows the contained object can no longer be used. ThePy_CLEAR()macro performs the operations in a safe order.If the
Py_TPFLAGS_MANAGED_DICTbit is set in thetp_flagsfield, the clear function must callPyObject_ClearManagedDict()like this:PyObject_ClearManagedDict((PyObject*)self);
Більше інформації про схему збирання сміття Python можна знайти в розділі Підтримка циклічного збирання сміття.
Наслідування:
Group:
Py_TPFLAGS_HAVE_GC,tp_traverse,tp_clearThis field is inherited by subtypes together with
tp_traverseand thePy_TPFLAGS_HAVE_GCflag bit: the flag bit,tp_traverse, andtp_clearare 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_Typeprovides atp_richcompareimplementation, which may be inherited. However, if onlytp_hashis defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.-
Py_LT¶
-
Py_ssize_t PyTypeObject.tp_weaklistoffset¶
While this field is still supported,
Py_TPFLAGS_MANAGED_WEAKREFshould 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 thePyWeakref_*functions. The instance structure needs to include a field of type PyObject* which is initialized toNULL.Не плутайте це поле з
tp_weaklist; це заголовок списку для слабких посилань на сам об’єкт типу.It is an error to set both the
Py_TPFLAGS_MANAGED_WEAKREFbit andtp_weaklistoffset.Наслідування:
Це поле успадковується підтипами, але перегляньте наведені нижче правила. Підтип може замінити це зміщення; це означає, що підтип використовує інший слабкий заголовок списку посилань, ніж базовий тип. Оскільки заголовок списку завжди можна знайти через
tp_weaklistoffset, це не повинно бути проблемою.За замовчуванням:
If the
Py_TPFLAGS_MANAGED_WEAKREFbit is set in thetp_flagsfield, thentp_weaklistoffsetwill 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_Typeis 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
NULLbefore PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. OncePyType_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 onPyInterpreterState. UsePyType_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_DICTshould 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_dictoffsetshould be regarded as write-only. To get the pointer to the dictionary callPyObject_GenericGetDict(). CallingPyObject_GenericGetDict()may need to allocate memory for the dictionary, so it is may be more efficient to callPyObject_GetAttr()when accessing an attribute on the object.It is an error to set both the
Py_TPFLAGS_MANAGED_DICTbit andtp_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
NULLthen no__dict__gets created for instances.If the
Py_TPFLAGS_MANAGED_DICTbit is set in thetp_flagsfield, thentp_dictoffsetwill 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 fromobject.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_INSTANTIATIONflag 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 fromobject. Exception: If the type supports garbage collection (i.e., thePy_TPFLAGS_HAVE_GCflag is set intp_flags) and it would inheritPyObject_Free(), then this slot is not inherited but instead defaults toPyObject_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 thePy_TPFLAGS_HAVE_GCflag.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_flagsfield, and check thePy_TPFLAGS_HAVE_GCflag 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 return1for a collectible instance, and0for 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_GCis used as the functional equivalent.
-
PyObject *PyTypeObject.tp_bases¶
Кортеж базових типів.
This field should be set to
NULLand treated as read-only. Python will fill it in when the type isinitialized.For dynamically created classes, the
Py_tp_basesslotcan be used instead of the bases argument ofPyType_FromSpecWithBases(). The argument form is preferred.Попередження
Multiple inheritance does not work well for statically defined types. If you set
tp_basesto 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
NULLand treated as read-only. Python will fill it in when the type isinitialized.Наслідування:
Це поле не успадковується; він обчислюється за допомогою
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 onPyInterpreterState. 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 callPyObject_CallFinalizerFromDealloc()at the beginning oftp_deallocto guarantee that the object is always finalized before destruction.Примітка
The
tp_finalizefunction can be called from any thread, although the GIL will be held.Примітка
The
tp_finalizefunction 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:
Python might mark the object as finalized. Currently, Python always marks objects whose type supports garbage collection (i.e., the
Py_TPFLAGS_HAVE_GCflag is set intp_flags) and never marks other types of objects; this might change in a future version.If the object is not marked as finalized and its
tp_finalizefinalizer function is non-NULL, the finalizer function is called.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.
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()orPyObject_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_GCflag is not set. Such objects can still be manually finalized by callingPyObject_CallFinalizer()orPyObject_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()orPyObject_CallFinalizerFromDealloc()instead.tp_finalizeshould 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 callingPyErr_GetRaisedException()and restore the exception at the end by callingPyErr_SetRaisedException(). If an exception is encountered in the middle of the finalizer, log and clear it withPyErr_WriteUnraisable()orPyErr_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_FINALIZEflags bit in order for this field to be used. This is no longer required.Дивись також
PEP 442: «Safe object finalization»
Object Life Cycle for details about how this slot relates to other slots.
-
vectorcallfunc PyTypeObject.tp_vectorcall¶
A vectorcall function to use for calls of this type object (rather than instances). In other words,
tp_vectorcallcan be used to optimizetype.__call__, which typically returns a new instance of type.As with any vectorcall function, if
tp_vectorcallisNULL, 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 thattype->tp_vectorcallmust match the behavior ofPy_TYPE(type)->tp_call.Specifically, if type uses the default metaclass,
type->tp_vectorcallmust behave the same as PyType_Type->tp_call, which:calls
type->tp_new,if the result is a subclass of type, calls
type->tp_initon the result oftp_new, andreturns the result of
tp_new.
Typically,
tp_vectorcallis overridden to optimize this process for specifictp_newandtp_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_reservedfield should always beNULL. It was previously callednb_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()andPySequence_DelSlice(). It has the same signature asPyObject_SetItem(), but v can also be set toNULLto delete an item. If this slot isNULL, 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_lengthslot is filled, it is called and the sequence length is used to compute a positive index which is passed tosq_item. Ifsq_lengthisNULL, 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), реалізація цієї функції ПОВИННА виконувати такі дії:
Check if the request can be met. If not, raise
BufferError, set view->obj toNULLand return-1.Заповніть необхідні поля.
Збільшити внутрішній лічильник для кількості експортів.
Set view->obj to exporter and increment view->obj.
Повернути
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. В іншому випадку стандартна реалізація цієї функції виконає наступні додаткові дії:Зменшити внутрішній лічильник для кількості експортів.
Якщо лічильник
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 toNULL.
-
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_refcntset to1andob_typeset to the type argument. If the type’stp_itemsizeis non-zero, the object’sob_sizefield should be initialized to nitems and the length of the allocated memory block should betp_basicsize + nitems*tp_itemsize, rounded up to a multiple ofsizeof(void*); otherwise, nitems is not used and the length of the block should betp_basicsize.Ця функція не повинна виконувати будь-яку іншу ініціалізацію екземпляра, навіть не для виділення додаткової пам’яті; це має зробити
tp_new.
-
typedef void (*destructor)(PyObject*)¶
- Part of the Stable ABI.
-
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 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 *),
};