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.
Type objects are fairly large compared to most of the standard types. The reason for the size is that each type object stores a large number of values, mostly C function pointers, each of which implements a small part of the type's functionality. The fields of the type object are examined in detail in this section. The fields will be described in the order in which they occur in the structure.
In addition to the following quick reference, the typedef-examples section provides at-a-glance insight into the meaning and use of PyTypeObject.
Quick Reference
"tp slots"
| PyTypeObject Slot1 | Type <slot-typedefs-table> |
special methods/attrs | Info2 | |||
|---|---|---|---|---|---|---|
| O | T | D | I | |||
<R> ~PyTypeObject.tp_name |
const char * | __name__ | X | X | ||
~PyTypeObject.tp_basicsize |
Py_ssize_t |
X | X | X | ||
~PyTypeObject.tp_itemsize |
Py_ssize_t |
X | X | |||
~PyTypeObject.tp_dealloc |
destructor |
X | X | X | ||
~PyTypeObject.tp_vectorcall_offset |
Py_ssize_t |
X | X | |||
(~PyTypeObject.tp_getattr) |
getattrfunc |
__getattribute__, __getattr__ | G | |||
(~PyTypeObject.tp_setattr) |
setattrfunc |
__setattr__, __delattr__ | G | |||
~PyTypeObject.tp_as_async |
PyAsyncMethods * |
sub-slots |
% | |||
~PyTypeObject.tp_repr |
reprfunc |
__repr__ | X | X | X | |
~PyTypeObject.tp_as_number |
PyNumberMethods * |
sub-slots |
% | |||
~PyTypeObject.tp_as_sequence |
PySequenceMethods * |
sub-slots |
% | |||
~PyTypeObject.tp_as_mapping |
PyMappingMethods * |
sub-slots |
% | |||
~PyTypeObject.tp_hash |
hashfunc |
__hash__ | X | G | ||
~PyTypeObject.tp_call |
ternaryfunc |
__call__ | X | X | ||
~PyTypeObject.tp_str |
reprfunc |
__str__ | X | X | ||
~PyTypeObject.tp_getattro |
getattrofunc |
__getattribute__, __getattr__ | X | X | G | |
~PyTypeObject.tp_setattro |
setattrofunc |
__setattr__, __delattr__ | X | X | G | |
~PyTypeObject.tp_as_buffer |
PyBufferProcs * |
sub-slots |
% | |||
~PyTypeObject.tp_flags |
unsigned long | X | X | ? | ||
~PyTypeObject.tp_doc |
const char * | __doc__ | X | X | ||
~PyTypeObject.tp_traverse |
traverseproc |
X | G | |||
~PyTypeObject.tp_clear |
inquiry |
X | G | |||
~PyTypeObject.tp_richcompare |
richcmpfunc |
__lt__, __le__, __eq__, __ne__, __gt__, __ge__ | X | G | ||
(~PyTypeObject.tp_weaklistoffset) |
Py_ssize_t |
X | ? | |||
~PyTypeObject.tp_iter |
getiterfunc |
__iter__ | X | |||
~PyTypeObject.tp_iternext |
iternextfunc |
__next__ | X | |||
~PyTypeObject.tp_methods |
PyMethodDef [] |
X | X | |||
~PyTypeObject.tp_members |
PyMemberDef [] |
X | ||||
~PyTypeObject.tp_getset |
PyGetSetDef [] |
X | X | |||
~PyTypeObject.tp_base |
PyTypeObject * |
__base__ | X | |||
~PyTypeObject.tp_dict |
PyObject * |
__dict__ | ? | |||
~PyTypeObject.tp_descr_get |
descrgetfunc |
__get__ | X | |||
~PyTypeObject.tp_descr_set |
descrsetfunc |
__set__, __delete__ | X | |||
(~PyTypeObject.tp_dictoffset) |
Py_ssize_t |
X | ? | |||
~PyTypeObject.tp_init |
initproc |
__init__ | X | X | X | |
~PyTypeObject.tp_alloc |
allocfunc |
X | ? | ? | ||
~PyTypeObject.tp_new |
newfunc |
__new__ | X | X | ? | ? |
~PyTypeObject.tp_free |
freefunc |
X | X | ? | ? | |
~PyTypeObject.tp_is_gc |
inquiry |
X | X | |||
<~PyTypeObject.tp_bases> |
PyObject * |
__bases__ | ~ | |||
<~PyTypeObject.tp_mro> |
PyObject * |
__mro__ | ~ | |||
[~PyTypeObject.tp_cache] |
PyObject * |
|||||
[~PyTypeObject.tp_subclasses] |
void * | __subclasses__ | ||||
[~PyTypeObject.tp_weaklist] |
PyObject * |
|||||
(~PyTypeObject.tp_del) |
destructor |
|||||
[~PyTypeObject.tp_version_tag] |
unsigned int | |||||
~PyTypeObject.tp_finalize |
destructor |
__del__ | X | |||
~PyTypeObject.tp_vectorcall |
vectorcallfunc |
|||||
[~PyTypeObject.tp_watched] |
unsigned char | |||||
(): A slot name in parentheses indicates it is (effectively) deprecated.
<>: Names in angle brackets should be initially set to
NULLand treated as read-only.[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-
NULL).↩︎Columns:
"O": set on
PyBaseObject_Type"T": set on
PyType_Type"D": default (if slot is set to
NULL)X - PyType_Ready sets this value if it is NULL ~ - PyType_Ready always sets this value (it should be NULL) ? - PyType_Ready may set this value depending on other slots Also see the inheritance column ("I")."I": inheritance
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value % - the slots of the sub-struct are inherited individually G - inherited, but only in combination with other slots; see the slot's description ? - it's complicated; see the slot's descriptionNote that some slots are effectively inherited through the normal attribute lookup chain.↩︎
sub-slots
| Slot | Type <slot-typedefs-table> |
special methods |
|---|---|---|
~PyAsyncMethods.am_await |
unaryfunc |
__await__ |
~PyAsyncMethods.am_aiter |
unaryfunc |
__aiter__ |
~PyAsyncMethods.am_anext |
unaryfunc |
__anext__ |
~PyAsyncMethods.am_send |
sendfunc |
|
~PyNumberMethods.nb_add |
binaryfunc |
__add__ __radd__ |
~PyNumberMethods.nb_inplace_add |
binaryfunc |
__iadd__ |
~PyNumberMethods.nb_subtract |
binaryfunc |
__sub__ __rsub__ |
~PyNumberMethods.nb_inplace_subtract |
binaryfunc |
__isub__ |
~PyNumberMethods.nb_multiply |
binaryfunc |
__mul__ __rmul__ |
~PyNumberMethods.nb_inplace_multiply |
binaryfunc |
__imul__ |
~PyNumberMethods.nb_remainder |
binaryfunc |
__mod__ __rmod__ |
~PyNumberMethods.nb_inplace_remainder |
binaryfunc |
__imod__ |
~PyNumberMethods.nb_divmod |
binaryfunc |
__divmod__ __rdivmod__ |
~PyNumberMethods.nb_power |
ternaryfunc |
__pow__ __rpow__ |
~PyNumberMethods.nb_inplace_power |
ternaryfunc |
__ipow__ |
~PyNumberMethods.nb_negative |
unaryfunc |
__neg__ |
~PyNumberMethods.nb_positive |
unaryfunc |
__pos__ |
~PyNumberMethods.nb_absolute |
unaryfunc |
__abs__ |
~PyNumberMethods.nb_bool |
inquiry |
__bool__ |
~PyNumberMethods.nb_invert |
unaryfunc |
__invert__ |
~PyNumberMethods.nb_lshift |
binaryfunc |
__lshift__ __rlshift__ |
~PyNumberMethods.nb_inplace_lshift |
binaryfunc |
__ilshift__ |
~PyNumberMethods.nb_rshift |
binaryfunc |
__rshift__ __rrshift__ |
~PyNumberMethods.nb_inplace_rshift |
binaryfunc |
__irshift__ |
~PyNumberMethods.nb_and |
binaryfunc |
__and__ __rand__ |
~PyNumberMethods.nb_inplace_and |
binaryfunc |
__iand__ |
~PyNumberMethods.nb_xor |
binaryfunc |
__xor__ __rxor__ |
~PyNumberMethods.nb_inplace_xor |
binaryfunc |
__ixor__ |
~PyNumberMethods.nb_or |
binaryfunc |
__or__ __ror__ |
~PyNumberMethods.nb_inplace_or |
binaryfunc |
__ior__ |
~PyNumberMethods.nb_int |
unaryfunc |
__int__ |
~PyNumberMethods.nb_reserved |
void * | |
~PyNumberMethods.nb_float |
unaryfunc |
__float__ |
~PyNumberMethods.nb_floor_divide |
binaryfunc |
__floordiv__ |
~PyNumberMethods.nb_inplace_floor_divide |
binaryfunc |
__ifloordiv__ |
~PyNumberMethods.nb_true_divide |
binaryfunc |
__truediv__ |
~PyNumberMethods.nb_inplace_true_divide |
binaryfunc |
__itruediv__ |
~PyNumberMethods.nb_index |
unaryfunc |
__index__ |
~PyNumberMethods.nb_matrix_multiply |
binaryfunc |
__matmul__ __rmatmul__ |
~PyNumberMethods.nb_inplace_matrix_multiply |
binaryfunc |
__imatmul__ |
~PyMappingMethods.mp_length |
lenfunc |
__len__ |
~PyMappingMethods.mp_subscript |
binaryfunc |
__getitem__ |
~PyMappingMethods.mp_ass_subscript |
objobjargproc |
__setitem__, __delitem__ |
~PySequenceMethods.sq_length |
lenfunc |
__len__ |
~PySequenceMethods.sq_concat |
binaryfunc |
__add__ |
~PySequenceMethods.sq_repeat |
ssizeargfunc |
__mul__ |
~PySequenceMethods.sq_item |
ssizeargfunc |
__getitem__ |
~PySequenceMethods.sq_ass_item |
ssizeobjargproc |
__setitem__ __delitem__ |
~PySequenceMethods.sq_contains |
objobjproc |
__contains__ |
~PySequenceMethods.sq_inplace_concat |
binaryfunc |
__iadd__ |
~PySequenceMethods.sq_inplace_repeat |
ssizeargfunc |
__imul__ |
~PyBufferProcs.bf_getbuffer |
getbufferproc |
__buffer__ |
~PyBufferProcs.bf_releasebuffer |
releasebufferproc |
__release_buffer__ |
slot typedefs
typedef |
Parameter Types |
Return Type |
|---|---|---|
|
PyTypeObject *Py_ssize_t |
|
|
|
void |
|
void * |
void |
|
PyObject *visitprocvoid * |
int |
|
PyTypeObject *PyObject *PyObject * |
|
|
PyObject *PyObject *PyObject * |
int |
|
|
|
|
PyObject *const char * |
|
|
PyObject *const char * PyObject * |
int |
|
PyObject *PyObject * |
|
|
PyObject *PyObject *PyObject * |
int |
|
PyObject *PyObject *PyObject * |
|
|
PyObject *PyObject *PyObject * |
int |
|
|
Py_hash_t |
|
PyObject *PyObject *int |
|
|
|
|
|
|
|
|
|
|
|
PyObject *Py_buffer *int |
int |
|
PyObject *Py_buffer * |
void |
|
|
int |
|
PyObject * |
|
|
PyObject *PyObject * |
|
|
PyObject *PyObject *PyObject * |
|
|
PyObject *Py_ssize_t |
|
|
PyObject *Py_ssize_tPyObject * |
int |
|
PyObject *PyObject * |
int |
|
PyObject *PyObject *PyObject * |
int |
See slot-typedefs below for more detail.
PyTypeObject Definition
The structure definition for PyTypeObject can be found in Include/cpython/object.h. For convenience of reference, this repeats the definition found there:
../includes/typestruct.h
PyObject Slots
The type object structure extends the PyVarObject structure. The ~PyVarObject.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 ~PyTypeObject.tp_itemsize, which means that its instances (i.e. type objects) must have the ~PyVarObject.ob_size field.
PyObject.ob_refcnt
The type object's reference count is initialized to
1by thePyObject_HEAD_INITmacro. Note that forstatically allocated type objects <static-types>, the type's instances (objects whose~PyObject.ob_typepoints back to the type) do not count as references. But fordynamically allocated type objects <heap-types>, the instances do count as references.Inheritance:
This field is not inherited by subtypes.
PyObject.ob_type
This is the type's type, in other words its metatype. It is initialized by the argument to the
PyObject_HEAD_INITmacro, and its value should normally be&PyType_Type. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid initializer. Therefore, the convention is to passNULLto thePyObject_HEAD_INITmacro and to initialize this field explicitly at the start of the module's initialization function, before doing anything else. This is typically done like this:Foo_Type.ob_type = &PyType_Type;This should be done before any instances of the type are created.
PyType_Readychecks if~PyObject.ob_typeisNULL, and if so, initializes it to the~PyObject.ob_typefield of the base class.PyType_Readywill not change this field if it is non-zero.Inheritance:
This field is inherited by subtypes.
PyVarObject Slots
PyVarObject.ob_size
For
statically allocated type objects <static-types>, this should be initialized to zero. Fordynamically allocated type objects <heap-types>, this field has a special internal meaning.This field should be accessed using the
Py_SIZE()macro.Inheritance:
This field is not inherited by subtypes.
PyTypeObject Slots
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.)
See
Py_tp_namefor the correspondingSlot ID <PySlot.sl_id>.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 module!Min subpackage!Qin package!Pshould have the~PyTypeObject.tp_nameinitializer"P.Q.M.T".For
dynamically allocated type objects <heap-types>, this should just be the type name, and the module name explicitly stored in the type dict as the value for key'__module__'.For
statically allocated type objects <static-types>, the tp_name field should contain a dot. Everything before the last dot is made accessible as the~type.__module__attribute, and everything after the last dot is made accessible as the~type.__name__attribute.If no dot is present, the entire
~PyTypeObject.tp_namefield is made accessible as the~type.__name__attribute, and the~type.__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.This field must not be
NULL. It is the only required field inPyTypeObject(other than potentially~PyTypeObject.tp_itemsize).Inheritance:
This field is not inherited by subtypes.
Py_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~PyTypeObject.tp_freefunction to free the object itself.If you may call functions that may set the error indicator, you must use
PyErr_GetRaisedExceptionandPyErr_SetRaisedExceptionto 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_FormatUnraisableto 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 (
~PyTypeObject.tp_finalize) subsequently resurrects the object.- An object will not be destroyed while it is being automatically finalized (
~PyTypeObject.tp_finalize) or automatically cleared (~PyTypeObject.tp_clear).CPython currently destroys an object immediately from
Py_DECREFwhen the new reference count is zero, but this may change in a future version.It is recommended to call
PyObject_CallFinalizerFromDeallocat the beginning of!tp_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_UnTrackbefore clearing any member fields.It is permissible to call
~PyTypeObject.tp_clearfrom!tp_deallocto reduce code duplication and to guarantee that the object is always cleared before destruction. Beware that!tp_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 which!tp_deallocis called with anattached 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_deallocwill not violate any assumptions of the library.Inheritance:
This field is inherited by subtypes.
life-cyclefor details about how this slot relates to other slots.
An optional offset to a per-instance function that implements calling the object using the
vectorcall protocol <vectorcall>, a more efficient alternative of the simpler~PyTypeObject.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 to~PyTypeObject.tp_call.Any class that sets
Py_TPFLAGS_HAVE_VECTORCALLmust also set~PyTypeObject.tp_calland make sure its behaviour is consistent with the vectorcallfunc function. This can be done by setting tp_call toPyVectorcall_Call.3.8
Before version 3.8, this slot was named
tp_print. In Python 2.x, it was used for printing to a file. In Python 3.0 to 3.7, it was unused.3.12
Before version 3.12, it was not recommended for
mutable heap types <heap-types>to implement the vectorcall protocol. When a user sets~object.__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.Inheritance:
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 usevectorcall <vectorcall>, except whenPyVectorcall_Callis explicitly called.
Py_tp_getattr
An optional pointer to the get-attribute-string function.
This field is deprecated. When it is defined, it should point to a function that acts the same as the
~PyTypeObject.tp_getattrofunction, but taking a C string instead of a Python string object to give the attribute name.Inheritance:
Group:
~PyTypeObject.tp_getattr,~PyTypeObject.tp_getattroThis field is inherited by subtypes together with
~PyTypeObject.tp_getattro: a subtype inherits both~PyTypeObject.tp_getattrand~PyTypeObject.tp_getattrofrom its base type when the subtype's~PyTypeObject.tp_getattrand~PyTypeObject.tp_getattroare bothNULL.
Py_tp_setattr
An optional pointer to the function for setting and deleting attributes.
This field is deprecated. When it is defined, it should point to a function that acts the same as the
~PyTypeObject.tp_setattrofunction, but taking a C string instead of a Python string object to give the attribute name.Inheritance:
Group:
~PyTypeObject.tp_setattr,~PyTypeObject.tp_setattroThis field is inherited by subtypes together with
~PyTypeObject.tp_setattro: a subtype inherits both~PyTypeObject.tp_setattrand~PyTypeObject.tp_setattrofrom its base type when the subtype's~PyTypeObject.tp_setattrand~PyTypeObject.tp_setattroare bothNULL.
Pointer to an additional structure that contains fields relevant only to objects which implement
awaitableandasynchronous iteratorprotocols at the C-level. Seeasync-structsfor details.3.5 Formerly known as
tp_compareandtp_reserved.Inheritance:
The
~PyTypeObject.tp_as_asyncfield is not inherited, but the contained fields are inherited individually.
Py_tp_repr
pair: built-in function; repr
An optional pointer to a function that implements the built-in function
repr.The signature is the same as for
PyObject_Repr:PyObject *tp_repr(PyObject *self);The function must return a string or a Unicode object. Ideally, this function should return a string that, when passed to
eval, given a suitable environment, returns an object with the same value. If this is not feasible, it should return a string starting with'<'and ending with'>'from which both the type and the value of the object can be deduced.Inheritance:
This field is inherited by subtypes.
Default:
When this field is not set, a string of the form
<%s object at %p>is returned, where%sis replaced by the type name, and%pby the object's memory address.
Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in
number-structs.Inheritance:
The
~PyTypeObject.tp_as_numberfield is not inherited, but the contained fields are inherited individually.
Pointer to an additional structure that contains fields relevant only to objects which implement the sequence protocol. These fields are documented in
sequence-structs.Inheritance:
The
~PyTypeObject.tp_as_sequencefield is not inherited, but the contained fields are inherited individually.
Pointer to an additional structure that contains fields relevant only to objects which implement the mapping protocol. These fields are documented in
mapping-structs.Inheritance:
The
~PyTypeObject.tp_as_mappingfield is not inherited, but the contained fields are inherited individually.
Py_tp_hash
pair: built-in function; hash
An optional pointer to a function that implements the built-in function
hash.The signature is the same as for
PyObject_Hash:Py_hash_t tp_hash(PyObject *);The value
-1should not be returned as a normal return value; when an error occurs during the computation of the hash value, the function should set an exception and return-1.When this field is not set (and
~PyTypeObject.tp_richcompareis not set), an attempt to take the hash of the object raisesTypeError. This is the same as setting it toPyObject_HashNotImplemented.This field can be set explicitly to
PyObject_HashNotImplementedto block inheritance of the hash method from a parent type. This is interpreted as the equivalent of__hash__ = Noneat the Python level, causingisinstance(o, collections.Hashable)to correctly returnFalse. Note that the converse is also true - setting__hash__ = Noneon a class at the Python level will result in thetp_hashslot being set toPyObject_HashNotImplemented.Inheritance:
Group:
~PyTypeObject.tp_hash,~PyTypeObject.tp_richcompareThis field is inherited by subtypes together with
~PyTypeObject.tp_richcompare: a subtype inherits both of~PyTypeObject.tp_richcompareand~PyTypeObject.tp_hash, when the subtype's~PyTypeObject.tp_richcompareand~PyTypeObject.tp_hashare bothNULL.Default:
PyBaseObject_TypeusesPyObject_GenericHash.
Py_tp_call
An optional pointer to a function that implements calling the object. This should be
NULLif the object is not callable. The signature is the same as forPyObject_Call:PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);Inheritance:
This field is inherited by subtypes.
Py_tp_str
An optional pointer to a function that implements the built-in operation
str. (Note thatstris a type now, andstrcalls the constructor for that type. This constructor callsPyObject_Strto do the actual work, andPyObject_Strwill call this handler.)The signature is the same as for
PyObject_Str:PyObject *tp_str(PyObject *self);The function must return a string or a Unicode object. It should be a "friendly" string representation of the object, as this is the representation that will be used, among other things, by the
Inheritance:
This field is inherited by subtypes.
Default:
When this field is not set,
PyObject_Repris called to return a string representation.
Py_tp_getattro
An optional pointer to the get-attribute function.
The signature is the same as for
PyObject_GetAttr:PyObject *tp_getattro(PyObject *self, PyObject *attr);It is usually convenient to set this field to
PyObject_GenericGetAttr, which implements the normal way of looking for object attributes.Inheritance:
Group:
~PyTypeObject.tp_getattr,~PyTypeObject.tp_getattroThis field is inherited by subtypes together with
~PyTypeObject.tp_getattr: a subtype inherits both~PyTypeObject.tp_getattrand~PyTypeObject.tp_getattrofrom its base type when the subtype's~PyTypeObject.tp_getattrand~PyTypeObject.tp_getattroare bothNULL.Default:
PyBaseObject_TypeusesPyObject_GenericGetAttr.
Py_tp_setattro
An optional pointer to the function for setting and deleting attributes.
The signature is the same as for
PyObject_SetAttr:int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);In addition, setting value to
NULLto delete an attribute must be supported. It is usually convenient to set this field toPyObject_GenericSetAttr, which implements the normal way of setting object attributes.Inheritance:
Group:
~PyTypeObject.tp_setattr,~PyTypeObject.tp_setattroThis field is inherited by subtypes together with
~PyTypeObject.tp_setattr: a subtype inherits both~PyTypeObject.tp_setattrand~PyTypeObject.tp_setattrofrom its base type when the subtype's~PyTypeObject.tp_setattrand~PyTypeObject.tp_setattroare bothNULL.Default:
PyBaseObject_TypeusesPyObject_GenericSetAttr.
Pointer to an additional structure that contains fields relevant only to objects which implement the buffer interface. These fields are documented in
buffer-structs.Inheritance:
The
~PyTypeObject.tp_as_bufferfield is not inherited, but the contained fields are inherited individually.
See
Py_tp_flagsfor the correspondingSlot ID <PySlot.sl_id>.This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain fields in the type object (or in the extension structures referenced via
~PyTypeObject.tp_as_number,~PyTypeObject.tp_as_sequence,~PyTypeObject.tp_as_mapping, and~PyTypeObject.tp_as_buffer) that were historically not always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must be considered to have a zero orNULLvalue instead.Inheritance:
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 the~PyTypeObject.tp_traverseand~PyTypeObject.tp_clearfields, i.e. if thePy_TPFLAGS_HAVE_GCflag bit is clear in the subtype and the~PyTypeObject.tp_traverseand~PyTypeObject.tp_clearfields in the subtype exist and haveNULLvalues.Default:
PyBaseObject_TypeusesPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.Bit Masks:
The following bit masks are currently defined; these can be ORed together using the
|operator to form the value of the~PyTypeObject.tp_flagsfield. The macroPyType_HasFeaturetakes a type and a flags value, tp and f, and checks whethertp->tp_flags & fis non-zero.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~PyObject.ob_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 alsosupport garbage collection <supporting-cycle-detection>as they can form a reference cycle with their own module object.Inheritance:
???
This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a "final" class in Java).
Inheritance:
???
This bit is set when the type object has been fully initialized by
PyType_Ready.Inheritance:
???
This bit is set while
PyType_Readyis in the process of initializing the type object.Inheritance:
???
This bit is set when the object supports garbage collection. If this bit is set, memory for new instances (see
~PyTypeObject.tp_alloc) must be allocated usingPyObject_GC_NeworPyType_GenericAllocand deallocated (see~PyTypeObject.tp_free) usingPyObject_GC_Del. More information in sectionsupporting-cycle-detection.Inheritance:
Group:
Py_TPFLAGS_HAVE_GC,~PyTypeObject.tp_traverse,~PyTypeObject.tp_clearThe
Py_TPFLAGS_HAVE_GCflag bit is inherited together with the~PyTypeObject.tp_traverseand~PyTypeObject.tp_clearfields, i.e. if thePy_TPFLAGS_HAVE_GCflag bit is clear in the subtype and the~PyTypeObject.tp_traverseand~PyTypeObject.tp_clearfields in the subtype exist and haveNULLvalues.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.Inheritance:
???
This bit indicates that objects behave like unbound methods.
If this flag is set for
type(meth), then:
meth.__get__(obj, cls)(*args, **kwds)(withobjnot None) must be equivalent tometh(obj, *args, **kwds).meth.__get__(None, cls)(*args, **kwds)must be equivalent tometh(*args, **kwds).This flag enables an optimization for typical method calls like
obj.meth(): it avoids creating a temporary "bound method" object forobj.meth.3.8
Inheritance:
This flag is never inherited by types without the
Py_TPFLAGS_IMMUTABLETYPEflag set. For extension types, it is inherited whenever~PyTypeObject.tp_descr_getis inherited.This bit indicates that instances of the class have a
~object.__dict__attribute, and that the space for the dictionary is managed by the VM.If this flag is set,
Py_TPFLAGS_HAVE_GCmust also be set.The type traverse function must call
PyObject_VisitManagedDictand its clear function must callPyObject_ClearManagedDict.3.12
Inheritance:
This flag is inherited unless the
~PyTypeObject.tp_dictoffsetfield is set in a superclass.This bit indicates that instances of the class should be weakly referenceable.
If this flag is set,
Py_TPFLAGS_HAVE_GCmust also be set.3.12
Inheritance:
This flag is inherited unless the
~PyTypeObject.tp_weaklistoffsetfield is set in a superclass.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.
3.12
Only usable with variable-size types, i.e. ones with non-zero
~PyTypeObject.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.
3.12
Inheritance:
This flag is inherited.
Functions such as
PyLong_Checkwill callPyType_FastSubclasswith one of these flags to quickly determine if a type is a subclass of a built-in type; such specific checks are faster than a generic check, likePyObject_IsInstance. Custom types that inherit from built-ins should have their~PyTypeObject.tp_flagsset appropriately, or the code that interacts with such types will behave differently depending on what kind of check is used.This bit is set when the
~PyTypeObject.tp_finalizeslot is present in the type structure.3.4
3.8 This flag isn't necessary anymore, as the interpreter assumes the
~PyTypeObject.tp_finalizeslot is always present in the type structure.This bit is set when the class implements the
vectorcall protocol <vectorcall>. See~PyTypeObject.tp_vectorcall_offsetfor details.Inheritance:
This bit is inherited if
~PyTypeObject.tp_callis also inherited.3.8 as
_Py_TPFLAGS_HAVE_VECTORCALL3.9
Renamed to the current name, without the leading underscore. The old provisional name is
soft deprecated.3.12
This flag is now removed from a class when the class's
~object.__call__method is reassigned.This flag can now be inherited by mutable classes.
This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.
PyType_Readyautomatically applies this flag tostatic types <static-types>.Inheritance:
This flag is not inherited.
3.10
Disallow creating instances of the type: set
~PyTypeObject.tp_newto NULL and don't create the__new__key in the type dictionary.The flag must be set before creating the type, not after. For example, it must be set before
PyType_Readyis called on the type.The flag is set automatically on
static types <static-types>if~PyTypeObject.tp_baseis NULL or&PyBaseObject_Typeand~PyTypeObject.tp_newis NULL.Inheritance:
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
~PyTypeObject.tp_new(which is only possible via the C API).[!NOTE] 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~PyTypeObject.tp_newonly succeed for subclasses.3.10
This bit indicates that instances of the class may match mapping patterns when used as the subject of a
matchblock. It is automatically set when registering or subclassingcollections.abc.Mapping, and unset when registeringcollections.abc.Sequence.[!NOTE]
Py_TPFLAGS_MAPPINGandPy_TPFLAGS_SEQUENCEare mutually exclusive; it is an error to enable both flags simultaneously.Inheritance:
This flag is inherited by types that do not already set
Py_TPFLAGS_SEQUENCE.
634-- Structural Pattern Matching: Specification3.10
This bit indicates that instances of the class may match sequence patterns when used as the subject of a
matchblock. It is automatically set when registering or subclassingcollections.abc.Sequence, and unset when registeringcollections.abc.Mapping.[!NOTE]
Py_TPFLAGS_MAPPINGandPy_TPFLAGS_SEQUENCEare mutually exclusive; it is an error to enable both flags simultaneously.Inheritance:
This flag is inherited by types that do not already set
Py_TPFLAGS_MAPPING.
634-- Structural Pattern Matching: Specification3.10
Internal. Do not set or unset this flag. To indicate that a class has changed call
PyType_Modified[!WARNING] This flag is present in header files, but is not be used. It will be removed in a future version of CPython
This macro does nothing. Historically, this would indicate that the
~PyTypeObject.tp_version_tagfield was available and initialized.3.13
This bit indicates that instances of this type will have an "inline values" array (containing the object's attributes) placed directly after the end of the object.
This requires that
Py_TPFLAGS_HAVE_GCis set.Inheritance:
This flag is not inherited.
3.13
This bit indicates that this is an abstract type and therefore cannot be instantiated.
Inheritance:
This flag is not inherited.
abcInternal. Do not set or unset this flag. Historically, this was a reserved flag for use in Stackless Python.
[!WARNING] This flag is present in header files, but is not be used. This may be removed in a future version of CPython.
Py_tp_doc
An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the
~type.__doc__attribute on the type and instances of the type.Inheritance:
This field is not inherited by subtypes.
Py_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.See
gc-traversalfor documentation.Inheritance:
Group:
Py_TPFLAGS_HAVE_GC,~PyTypeObject.tp_traverse,~PyTypeObject.tp_clearThis field is inherited by subtypes together with
~PyTypeObject.tp_clearand thePy_TPFLAGS_HAVE_GCflag bit: the flag bit,~PyTypeObject.tp_traverse, and~PyTypeObject.tp_clearare all inherited from the base type if they are all zero in the subtype.
Py_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 isolateso 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's~PyTypeObject.tp_deallocfunction to invoke!tp_clearto avoid code duplication. (Beware that!tp_clearmight have already been called. Prefer calling idempotent functions likePy_CLEAR.)Any non-trivial cleanup should be performed in
~PyTypeObject.tp_finalizeinstead of!tp_clear.[!NOTE] If
!tp_clearfails to break a reference cycle then the objects in thecyclic isolatemay remain indefinitely uncollectable ("leak"). Seegc.garbage.[!NOTE] Referents (direct and indirect) might have already been cleared; they are not guaranteed to be in a consistent state.
[!NOTE] The
~PyTypeObject.tp_clearfunction can be called from any thread.[!NOTE] An object is not guaranteed to be automatically cleared before its destructor (
~PyTypeObject.tp_dealloc) is called.This function differs from the destructor (
~PyTypeObject.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
~PyTypeObject.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 (~PyTypeObject.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 acyclic 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
~PyTypeObject.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 (~PyTypeObject.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 while!tp_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
~PyTypeObject.tp_clearfunctions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply a~PyTypeObject.tp_clearfunction. For example, the tuple type does not implement a~PyTypeObject.tp_clearfunction, because it's possible to prove that no reference cycle can be composed entirely of tuples. Therefore the~PyTypeObject.tp_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 implementing~PyTypeObject.tp_clear.Implementations of
~PyTypeObject.tp_clearshould drop the instance's references to those of its members that may be Python objects, and set its pointers to those members toNULL, as in the following example: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_CLEARmacro 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_CLEARmacro performs the operations in a safe order.If the
Py_TPFLAGS_MANAGED_DICTbit is set in the~PyTypeObject.tp_flagsfield, the clear function must callPyObject_ClearManagedDictlike this:PyObject_ClearManagedDict((PyObject*)self);More information about Python's garbage collection scheme can be found in section
supporting-cycle-detection.Inheritance:
Group:
Py_TPFLAGS_HAVE_GC,~PyTypeObject.tp_traverse,~PyTypeObject.tp_clearThis field is inherited by subtypes together with
~PyTypeObject.tp_traverseand thePy_TPFLAGS_HAVE_GCflag bit: the flag bit,~PyTypeObject.tp_traverse, and~PyTypeObject.tp_clearare all inherited from the base type if they are all zero in the subtype.
life-cyclefor details about how this slot relates to other slots.
Py_tp_richcompare
An optional pointer to the rich comparison function, whose signature is:
PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);The first parameter is guaranteed to be an instance of the type that is defined by
PyTypeObject.The function should return the result of the comparison (usually
Py_TrueorPy_False). If the comparison is undefined, it must returnPy_NotImplemented, if another error occurred it must returnNULLand set an exception condition.The following constants are defined to be used as the third argument for
~PyTypeObject.tp_richcompareand forPyObject_RichCompare:
Constant Comparison <<===!=>>=The following macro is defined to ease writing rich comparison functions:
Return
Py_TrueorPy_Falsefrom the function, depending on the result of a comparison. VAL_A and VAL_B must be orderable by C comparison operators (for example, they may be C ints or floats). The third argument specifies the requested operation, as forPyObject_RichCompare.The returned value is a new
strong reference.On error, sets an exception and returns
NULLfrom the function.3.7
Inheritance:
Group:
~PyTypeObject.tp_hash,~PyTypeObject.tp_richcompareThis field is inherited by subtypes together with
~PyTypeObject.tp_hash: a subtype inherits~PyTypeObject.tp_richcompareand~PyTypeObject.tp_hashwhen the subtype's~PyTypeObject.tp_richcompareand~PyTypeObject.tp_hashare bothNULL.Default:
PyBaseObject_Typeprovides a~PyTypeObject.tp_richcompareimplementation, which may be inherited. However, if only~PyTypeObject.tp_hashis defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.
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_ClearWeakRefsand thePyWeakref_*functions. The instance structure needs to include a field of typePyObject*which is initialized toNULL.Do not confuse this field with
~PyTypeObject.tp_weaklist; that is the list head for weak references to the type object itself.It is an error to set both the
Py_TPFLAGS_MANAGED_WEAKREFbit and~PyTypeObject.tp_weaklistoffset.Inheritance:
This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype uses a different weak reference list head than the base type. Since the list head is always found via
~PyTypeObject.tp_weaklistoffset, this should not be a problem.Default:
If the
Py_TPFLAGS_MANAGED_WEAKREFbit is set in the~PyTypeObject.tp_flagsfield, then~PyTypeObject.tp_weaklistoffsetwill be set to a negative value, to indicate that it is unsafe to use this field.
Py_tp_iter
An optional pointer to a function that returns an
iteratorfor the object. Its presence normally signals that the instances of this type areiterable(although sequences may be iterable without this function).This function has the same signature as
PyObject_GetIter:PyObject *tp_iter(PyObject *self);Inheritance:
This field is inherited by subtypes.
Py_tp_iternext
An optional pointer to a function that returns the next item in an
iterator. The signature is:PyObject *tp_iternext(PyObject *self);When the iterator is
exhausted, thetp_iternextfunction must returnNULL; aStopIterationexception may or may not be set. When another error occurs, it must returnNULLtoo. The presence oftp_iternextsignals that the instances of this type are iterators.Iterator types should also define the
~PyTypeObject.tp_iterfunction, and that function should return the iterator instance itself (not a new iterator instance).This function has the same signature as
PyIter_Next.Inheritance:
This field is inherited by subtypes.
Py_tp_methods
An optional pointer to a static
NULL-terminated array ofPyMethodDefstructures, declaring regular methods of this type.For each entry in the array, an entry is added to the type's dictionary (see
~PyTypeObject.tp_dictbelow) containing a method descriptor.Inheritance:
This field is not inherited by subtypes (methods are inherited through a different mechanism).
Py_tp_members
An optional pointer to a static
NULL-terminated array ofPyMemberDefstructures, declaring regular data members (fields or slots) of instances of this type.For each entry in the array, an entry is added to the type's dictionary (see
~PyTypeObject.tp_dictbelow) containing a member descriptor.Inheritance:
This field is not inherited by subtypes (members are inherited through a different mechanism).
Py_tp_getset
An optional pointer to a static
NULL-terminated array ofPyGetSetDefstructures, declaring computed attributes of instances of this type.For each entry in the array, an entry is added to the type's dictionary (see
~PyTypeObject.tp_dictbelow) containing a getset descriptor.Inheritance:
This field is not inherited by subtypes (computed attributes are inherited through a different mechanism).
An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance is supported; multiple inheritance require dynamically creating a type object by calling the metatype.
For the corresponding slot ID, see
Py_tp_base.[!NOTE] Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be "address constants". Function designators like
PyType_GenericNew, with implicit conversion to a pointer, are valid C99 address constants.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.Consequently,
~PyTypeObject.tp_baseshould be set in the extension module's init function.Inheritance:
This field is not inherited by subtypes (obviously).
Default:
This field defaults to
&PyBaseObject_Type(which to Python programmers is known as the typeobject).
The type's dictionary is stored here by
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_Readyhas initialized the type, extra attributes for the type may be added to this dictionary only if they don't correspond to overloaded operations (like~object.__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_GetDictto 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_GetDictto get the dict for an arbitrary type.Inheritance:
This field is not inherited by subtypes (though the attributes defined in here are inherited through a different mechanism).
Default:
If this field is
NULL,PyType_Readywill assign a new dictionary to it.[!WARNING] It is not safe to use
PyDict_SetItemon or otherwise modify~PyTypeObject.tp_dictwith the dictionary C-API.
Py_tp_descr_get
An optional pointer to a "descriptor get" function.
The function signature is:
PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);Inheritance:
This field is inherited by subtypes.
Py_tp_descr_set
An optional pointer to a function for setting and deleting a descriptor's value.
The function signature is:
int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);The value argument is set to
NULLto delete the value.Inheritance:
This field is inherited by subtypes.
While this field is still supported,
Py_TPFLAGS_MANAGED_DICTshould be used instead, if at all possible.If the instances of this type have a dictionary containing instance variables, this field is non-zero and contains the offset in the instances of the type of the instance variable dictionary; this offset is used by
PyObject_GenericGetAttr.Do not confuse this field with
~PyTypeObject.tp_dict; that is the dictionary for attributes of the type object itself.The value specifies the offset of the dictionary from the start of the instance structure.
The
~PyTypeObject.tp_dictoffsetshould be regarded as write-only. To get the pointer to the dictionary callPyObject_GenericGetDict. CallingPyObject_GenericGetDictmay need to allocate memory for the dictionary, so it is may be more efficient to callPyObject_GetAttrwhen accessing an attribute on the object.It is an error to set both the
Py_TPFLAGS_MANAGED_DICTbit and~PyTypeObject.tp_dictoffset.Inheritance:
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.Default:
This slot has no default. For
static types <static-types>, if the field isNULLthen no~object.__dict__gets created for instances.If the
Py_TPFLAGS_MANAGED_DICTbit is set in the~PyTypeObject.tp_flagsfield, then~PyTypeObject.tp_dictoffsetwill be set to-1, to indicate that it is unsafe to use this field.
Py_tp_init
An optional pointer to an instance initialization function.
This function corresponds to the
~object.__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.The function signature is:
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
~object.__init__.The
~PyTypeObject.tp_initfunction, if notNULL, is called when an instance is created normally by calling its type, after the type's~PyTypeObject.tp_newfunction has returned an instance of the type. If the~PyTypeObject.tp_newfunction returns an instance of some other type that is not a subtype of the original type, no~PyTypeObject.tp_initfunction is called; if~PyTypeObject.tp_newreturns an instance of a subtype of the original type, the subtype's~PyTypeObject.tp_initis called.Returns
0on success,-1and sets an exception on error.Inheritance:
This field is inherited by subtypes.
Default:
For
static types <static-types>this field does not have a default.
Py_tp_alloc
An optional pointer to an instance allocation function.
The function signature is:
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);Inheritance:
Static subtypes inherit this slot, which will be
PyType_GenericAllocif inherited fromobject.
Heap subtypes <heap-types>do not inherit this slot.Default:
For heap subtypes, this field is always set to
PyType_GenericAlloc.For static subtypes, this slot is inherited (see above).
Py_tp_new
An optional pointer to an instance creation function.
The function signature is:
PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);The subtype argument is the type of the object being created; the args and kwds arguments represent positional and keyword arguments of the call to the type. Note that subtype doesn't have to equal the type whose
~PyTypeObject.tp_newfunction is called; it may be a subtype of that type (but not an unrelated type).The
~PyTypeObject.tp_newfunction should callsubtype->tp_alloc(subtype, nitems)to allocate space for the object, and then do only as much further initialization as is absolutely necessary. Initialization that can safely be ignored or repeated should be placed in the~PyTypeObject.tp_inithandler. A good rule of thumb is that for immutable types, all initialization should take place in~PyTypeObject.tp_new, while for mutable types, most initialization should be deferred to~PyTypeObject.tp_init.Set the
Py_TPFLAGS_DISALLOW_INSTANTIATIONflag to disallow creating instances of the type in Python.Inheritance:
This field is inherited by subtypes, except it is not inherited by
static types <static-types>whose~PyTypeObject.tp_baseisNULLor&PyBaseObject_Type.Default:
For
static types <static-types>this field has no default. This means if the slot is defined asNULL, the type cannot be called to create new instances; presumably there is some other way to create instances, like a factory function.
Py_tp_free
An optional pointer to an instance deallocation function. Its signature is:
void tp_free(void *self);This function must free the memory allocated by
~PyTypeObject.tp_alloc.Inheritance:
Static subtypes inherit this slot, which will be
PyObject_Freeif inherited fromobject. Exception: If the type supports garbage collection (i.e., thePy_TPFLAGS_HAVE_GCflag is set in~PyTypeObject.tp_flags) and it would inheritPyObject_Free, then this slot is not inherited but instead defaults toPyObject_GC_Del.
Heap subtypes <heap-types>do not inherit this slot.Default:
For
heap subtypes <heap-types>, this slot defaults to a deallocator suitable to matchPyType_GenericAllocand the value of thePy_TPFLAGS_HAVE_GCflag.For static subtypes, this slot is inherited (see above).
Py_tp_is_gc
An optional pointer to a function called by the garbage collector.
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
~PyTypeObject.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);(The only example of this are types themselves. The metatype,
PyType_Type, defines this function to distinguish between statically anddynamically allocated types <heap-types>.)Inheritance:
This field is inherited by subtypes.
Default:
This slot has no default. If this field is
NULL,Py_TPFLAGS_HAVE_GCis used as the functional equivalent.
Tuple of base types.
This field should be set to
NULLand treated as read-only. Python will fill it in when the type isinitialized <PyType_Ready>.For the corresponding slot ID, see
Py_tp_bases.[!WARNING] 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.Inheritance:
This field is not inherited.
Tuple containing the expanded set of base types, starting with the type itself and ending with
object, in Method Resolution Order.This field should be set to
NULLand treated as read-only. Python will fill it in when the type isinitialized <PyType_Ready>.Inheritance:
This field is not inherited; it is calculated fresh by
PyType_Ready.
Unused. Internal use only.
Inheritance:
This field is not inherited.
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method
~type.__subclasses__.3.12
For some types, this field does not hold a valid
PyObject*. The type was changed tovoid*to indicate this.Inheritance:
This field is not inherited.
Weak reference list head, for weak references to this type object. Not inherited. Internal use only.
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.Inheritance:
This field is not inherited.
Py_tp_del
This field is deprecated. Use
~PyTypeObject.tp_finalizeinstead.
Used to index into the method cache. Internal use only.
Inheritance:
This field is not inherited.
Py_tp_finalize
An optional pointer to an instance finalization function. This is the C implementation of the
~object.__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 (
~PyTypeObject.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).
[!NOTE] After Python automatically finalizes an object, Python might start automatically clearing (
~PyTypeObject.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.[!NOTE] An object is not guaranteed to be automatically finalized before its destructor (
~PyTypeObject.tp_dealloc) is called. It is recommended to callPyObject_CallFinalizerFromDeallocat the beginning of!tp_deallocto guarantee that the object is always finalized before destruction.[!NOTE] The
~PyTypeObject.tp_finalizefunction can be called from any thread, although theGILwill be held.[!NOTE] The
!tp_finalizefunction can be called during shutdown, after some global variables have been deleted. See the documentation of the~object.__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 in~PyTypeObject.tp_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_CallFinalizerorPyObject_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_CallFinalizerorPyObject_CallFinalizerFromDealloc.- Python will not automatically finalize any two members of a
cyclic isolateconcurrently.- Python will not automatically finalize an object after it has automatically cleared (
~PyTypeObject.tp_clear) the object.- If an object is a member of a
cyclic isolate, Python will not automatically finalize it after automatically clearing (see~PyTypeObject.tp_clear) any other member.- Python will automatically finalize every member of a
cyclic isolatebefore it automatically clears (see~PyTypeObject.tp_clear) any of them.- If Python is going to automatically clear an object (
~PyTypeObject.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_CallFinalizerorPyObject_CallFinalizerFromDeallocinstead.
~PyTypeObject.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_GetRaisedExceptionand 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_WriteUnraisableorPyErr_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); }Inheritance:
This field is inherited by subtypes.
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.
442: "Safe object finalization"life-cyclefor details about how this slot relates to other slots.PyObject_CallFinalizerPyObject_CallFinalizerFromDealloc
Py_tp_vectorcall
A
vectorcall function <vectorcall>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.[!NOTE] The
vectorcall protocol <vectorcall>requires that the vectorcall function has the same behavior as the correspondingtp_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 asPyType_Type->tp_call, which:
- calls
type->tp_new,- if the result is a subclass of type, calls
type->tp_initon the result oftp_new, and- returns the result of
tp_new.Typically,
tp_vectorcallis overridden to optimize this process for specific~PyTypeObject.tp_newand~PyTypeObject.tp_init. When doing this for user-subclassable types, note that both can be overridden (using~object.__new__and~object.__init__, respectively).Inheritance:
This field is never inherited.
3.9 (the field exists since 3.8 but it's only used since 3.9)
Internal. Do not use.
3.12
Static Types
Traditionally, types defined in C code are static, that is, a static PyTypeObject structure is defined directly in code and initialized using PyType_Ready.
This results in types that are limited relative to types defined in Python:
- Static types are limited to one base, i.e. they cannot use multiple inheritance.
- Static type objects (but not necessarily their instances) are immutable. It is not possible to add or modify the type object's attributes from Python.
- Static type objects are shared across
sub-interpreters <sub-interpreter-support>, so they should not include any subinterpreter-specific state.
Also, since PyTypeObject is only part of the Limited API <limited-c-api> as an opaque struct, any extension modules using static types must be compiled for a specific Python minor version.
Heap Types
An alternative to static types <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.
Number Object Structures
This structure holds pointers to the functions which an object uses to implement the number protocol. Each function is used by the function of similar name documented in the
numbersection.Here is the structure definition:
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;[!NOTE] Binary and ternary functions must check the type of all their operands, and implement the necessary conversions (at least one of the operands is an instance of the defined type). If the operation is not defined for the given operands, binary and ternary functions must return
Py_NotImplemented, if another error occurred they must returnNULLand set an exception.[!NOTE] The
~PyNumberMethods.nb_reservedfield should always beNULL. It was previously called!nb_long, and was renamed in Python 3.0.1.
Py_nb_add
Py_nb_subtract
Py_nb_multiply
Py_nb_remainder
Py_nb_divmod
Py_nb_power
Py_nb_negative
Py_nb_positive
Py_nb_absolute
Py_nb_bool
Py_nb_invert
Py_nb_lshift
Py_nb_rshift
Py_nb_and
Py_nb_xor
Py_nb_or
Py_nb_int
Py_nb_float
Py_nb_inplace_add
Py_nb_inplace_subtract
Py_nb_inplace_multiply
Py_nb_inplace_remainder
Py_nb_inplace_power
Py_nb_inplace_lshift
Py_nb_inplace_rshift
Py_nb_inplace_and
Py_nb_inplace_xor
Py_nb_inplace_or
Py_nb_floor_divide
Py_nb_true_divide
Py_nb_inplace_floor_divide
Py_nb_inplace_true_divide
Py_nb_index
Py_nb_matrix_multiply
Py_nb_inplace_matrix_multiply
Mapping Object Structures
This structure holds pointers to the functions which an object uses to implement the mapping protocol. It has three members:
Py_mp_length
This function is used by
PyMapping_SizeandPyObject_Size, and has the same signature. This slot may be set toNULLif the object has no defined length.
Py_mp_subscript
This function is used by
PyObject_GetItemandPySequence_GetSlice, and has the same signature as!PyObject_GetItem. This slot must be filled for thePyMapping_Checkfunction to return1, it can beNULLotherwise.
Py_mp_ass_subscript
This function is used by
PyObject_SetItem,PyObject_DelItem,PySequence_SetSliceandPySequence_DelSlice. It has the same signature as!PyObject_SetItem, but v can also be set toNULLto delete an item. If this slot isNULL, the object does not support item assignment and deletion.
Sequence Object Structures
This structure holds pointers to the functions which an object uses to implement the sequence protocol.
Py_sq_length
This function is used by
PySequence_SizeandPyObject_Size, and has the same signature. It is also used for handling negative indices via the~PySequenceMethods.sq_itemand the~PySequenceMethods.sq_ass_itemslots.
Py_sq_concat
This function is used by
PySequence_Concatand has the same signature. It is also used by the+operator, after trying the numeric addition via the~PyNumberMethods.nb_addslot.
Py_sq_repeat
This function is used by
PySequence_Repeatand has the same signature. It is also used by the*operator, after trying numeric multiplication via the~PyNumberMethods.nb_multiplyslot.
Py_sq_item
This function is used by
PySequence_GetItemand has the same signature. It is also used byPyObject_GetItem, after trying the subscription via the~PyMappingMethods.mp_subscriptslot. This slot must be filled for thePySequence_Checkfunction to return1, it can beNULLotherwise.Negative indexes are handled as follows: if the
~PySequenceMethods.sq_lengthslot is filled, it is called and the sequence length is used to compute a positive index which is passed to~PySequenceMethods.sq_item. If!sq_lengthisNULL, the index is passed as is to the function.
Py_sq_ass_item
This function is used by
PySequence_SetItemand has the same signature. It is also used byPyObject_SetItemandPyObject_DelItem, after trying the item assignment and deletion via the~PyMappingMethods.mp_ass_subscriptslot. This slot may be left toNULLif the object does not support item assignment and deletion.
Py_sq_contains
This function may be used by
PySequence_Containsand has the same signature. This slot may be left toNULL, in this case!PySequence_Containssimply traverses the sequence until it finds a match.
Py_sq_inplace_concat
This function is used by
PySequence_InPlaceConcatand has the same signature. It should modify its first operand, and return it. This slot may be left toNULL, in this case!PySequence_InPlaceConcatwill fall back toPySequence_Concat. It is also used by the augmented assignment+=, after trying numeric in-place addition via the~PyNumberMethods.nb_inplace_addslot.
Py_sq_inplace_repeat
This function is used by
PySequence_InPlaceRepeatand has the same signature. It should modify its first operand, and return it. This slot may be left toNULL, in this case!PySequence_InPlaceRepeatwill fall back toPySequence_Repeat. It is also used by the augmented assignment*=, after trying numeric in-place multiplication via the~PyNumberMethods.nb_inplace_multiplyslot.
Buffer Object Structures
This structure holds pointers to the functions required by the
Buffer protocol <bufferobjects>. The protocol defines how an exporter object can expose its internal data to consumer objects.
Py_bf_getbuffer
The signature of this function is:
int (PyObject *exporter, Py_buffer *view, int flags);Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this function MUST take these steps:
- Check if the request can be met. If not, raise
BufferError, setview->objtoNULLand return-1.- Fill in the requested fields.
- Increment an internal counter for the number of exports.
- Set
view->objto exporter and incrementview->obj.- Return
0.Thread safety:
In the
free-threaded build, implementations must ensure:
- The export counter increment in step (3) is atomic.
- The underlying buffer data remains valid and at a stable memory location for the lifetime of all exports.
- For objects that support resizing or reallocation (such as
bytearray), the export counter is checked atomically before such operations, andBufferErroris raised if exports exist.- The function is safe to call concurrently from multiple threads.
See also
thread-safety-memoryviewfor the Python-level thread safety guarantees ofmemoryviewobjects.If exporter is part of a chain or tree of buffer providers, two main schemes can be used:
- Re-export: Each member of the tree acts as the exporting object and sets
view->objto a new reference to itself.- Redirect: The buffer request is redirected to the root object of the tree. Here,
view->objwill be a new reference to the root object.The individual fields of view are described in section
Buffer structure <buffer-structure>, the rules how an exporter must react to specific requests are in sectionBuffer request types <buffer-request-types>.All memory pointed to in the
Py_bufferstructure belongs to the exporter and must remain valid until there are no consumers left.~Py_buffer.format,~Py_buffer.shape,~Py_buffer.strides,~Py_buffer.suboffsetsand~Py_buffer.internalare read-only for the consumer.
PyBuffer_FillInfoprovides an easy way of exposing a simple bytes buffer while dealing correctly with all request types.
PyObject_GetBufferis the interface for the consumer that wraps this function.
Py_bf_releasebuffer
The signature of this function is:
void (PyObject *exporter, Py_buffer *view);Handle a request to release the resources of the buffer. If no resources need to be released,
PyBufferProcs.bf_releasebuffermay beNULL. Otherwise, a standard implementation of this function will take these optional steps:
- Decrement an internal counter for the number of exports.
- If the counter is
0, free all memory associated with view.Thread safety:
In the
free-threaded build:
- The export counter decrement in step (1) must be atomic.
- Resource cleanup when the counter reaches zero must be done atomically, as the final release may race with concurrent releases from other threads and deallocation must only happen once.
The exporter MUST use the
~Py_buffer.internalfield to keep track of buffer-specific resources. This field is guaranteed to remain constant, while a consumer MAY pass a copy of the original buffer as the view argument.This function MUST NOT decrement
view->obj, since that is done automatically inPyBuffer_Release(this scheme is useful for breaking reference cycles).
PyBuffer_Releaseis the interface for the consumer that wraps this function.
Async Object Structures
3.5
This structure holds pointers to the functions required to implement
awaitableandasynchronous iteratorobjects.Here is the structure definition:
typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; sendfunc am_send; } PyAsyncMethods;
Py_am_await
The signature of this function is:
PyObject *am_await(PyObject *self);The returned object must be an
iterator, i.e.PyIter_Checkmust return1for it.This slot may be set to
NULLif an object is not anawaitable.
Py_am_aiter
The signature of this function is:
PyObject *am_aiter(PyObject *self);Must return an
asynchronous iteratorobject. See~object.__anext__for details.This slot may be set to
NULLif an object does not implement asynchronous iteration protocol.
Py_am_anext
The signature of this function is:
PyObject *am_anext(PyObject *self);Must return an
awaitableobject. See~object.__anext__for details. This slot may be set toNULL.
Py_am_send
The signature of this function is:
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);See
PyIter_Sendfor details. This slot may be set toNULL.3.10
Slot Type typedefs
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
~PyObject.ob_refcntset to1and~PyObject.ob_typeset to the type argument. If the type's~PyTypeObject.tp_itemsizeis non-zero, the object's~PyVarObject.ob_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 be~PyTypeObject.tp_basicsize.This function should not do any other instance initialization, not even to allocate additional memory; that should be done by
~PyTypeObject.tp_new.
See
~PyTypeObject.tp_free.
See
~PyTypeObject.tp_new.
See
~PyTypeObject.tp_init.
See
~PyTypeObject.tp_repr.
Return the value of the named attribute for the object.
Set the value of the named attribute for the object. The value argument is set to
NULLto delete the attribute.
Return the value of the named attribute for the object.
See
~PyTypeObject.tp_getattro.
Set the value of the named attribute for the object. The value argument is set to
NULLto delete the attribute.See
~PyTypeObject.tp_setattro.
See
~PyTypeObject.tp_descr_get.
See
~PyTypeObject.tp_descr_set.
See
~PyTypeObject.tp_hash.
See
~PyTypeObject.tp_richcompare.
See
~PyTypeObject.tp_iter.
See
~PyTypeObject.tp_iternext.
See
~PyAsyncMethods.am_send.
Examples
The following are simple examples of Python type definitions. They include common usage you may encounter. Some demonstrate tricky corner cases. For more examples, practical info, and a tutorial, see defining-new-types and new-types-topics.
A basic static type <static-types>:
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,
};
You may also find older code (especially in the CPython code base) with a more verbose initializer:
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 */
};
A type that supports weakrefs, instance dicts, and hashing:
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,
};
The simplest static type <static-types> with fixed-length instances:
typedef struct {
PyObject_HEAD
} MyObject;
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
};
The simplest static type <static-types> with variable-length instances:
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 *),
};
谢谢你的反馈!