• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _type-structs:
4
5Type Objects
6============
7
8Perhaps one of the most important structures of the Python object system is the
9structure that defines a new type: the :c:type:`PyTypeObject` structure.  Type
10objects can be handled using any of the :c:func:`PyObject_\*` or
11:c:func:`PyType_\*` functions, but do not offer much that's interesting to most
12Python applications. These objects are fundamental to how objects behave, so
13they are very important to the interpreter itself and to any extension module
14that implements new types.
15
16Type objects are fairly large compared to most of the standard types. The reason
17for the size is that each type object stores a large number of values, mostly C
18function pointers, each of which implements a small part of the type's
19functionality.  The fields of the type object are examined in detail in this
20section.  The fields will be described in the order in which they occur in the
21structure.
22
23In addition to the following quick reference, the :ref:`typedef-examples`
24section provides at-a-glance insight into the meaning and use of
25:c:type:`PyTypeObject`.
26
27
28Quick Reference
29---------------
30
31.. _tp-slots-table:
32
33"tp slots"
34^^^^^^^^^^
35
36.. table::
37   :widths: 18,18,18,1,1,1,1
38
39   +------------------------------------------------+-----------------------------------+-------------------+---------------+
40   | PyTypeObject Slot [#slots]_                    | :ref:`Type <slot-typedefs-table>` | special           | Info [#cols]_ |
41   |                                                |                                   | methods/attrs     +---+---+---+---+
42   |                                                |                                   |                   | O | T | D | I |
43   +================================================+===================================+===================+===+===+===+===+
44   | <R> :c:member:`~PyTypeObject.tp_name`          | const char *                      | __name__          | X | X |   |   |
45   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
46   | :c:member:`~PyTypeObject.tp_basicsize`         | Py_ssize_t                        |                   | X | X |   | X |
47   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
48   | :c:member:`~PyTypeObject.tp_itemsize`          | Py_ssize_t                        |                   |   | X |   | X |
49   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
50   | :c:member:`~PyTypeObject.tp_dealloc`           | :c:type:`destructor`              |                   | X | X |   | X |
51   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
52   | :c:member:`~PyTypeObject.tp_vectorcall_offset` | Py_ssize_t                        |                   |   | X |   | X |
53   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
54   | (:c:member:`~PyTypeObject.tp_getattr`)         | :c:type:`getattrfunc`             | __getattribute__, |   |   |   | G |
55   |                                                |                                   | __getattr__       |   |   |   |   |
56   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
57   | (:c:member:`~PyTypeObject.tp_setattr`)         | :c:type:`setattrfunc`             | __setattr__,      |   |   |   | G |
58   |                                                |                                   | __delattr__       |   |   |   |   |
59   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
60   | :c:member:`~PyTypeObject.tp_as_async`          | :c:type:`PyAsyncMethods` *        | :ref:`sub-slots`  |   |   |   | % |
61   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
62   | :c:member:`~PyTypeObject.tp_repr`              | :c:type:`reprfunc`                | __repr__          | X | X |   | X |
63   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
64   | :c:member:`~PyTypeObject.tp_as_number`         | :c:type:`PyNumberMethods` *       | :ref:`sub-slots`  |   |   |   | % |
65   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
66   | :c:member:`~PyTypeObject.tp_as_sequence`       | :c:type:`PySequenceMethods` *     | :ref:`sub-slots`  |   |   |   | % |
67   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
68   | :c:member:`~PyTypeObject.tp_as_mapping`        | :c:type:`PyMappingMethods` *      | :ref:`sub-slots`  |   |   |   | % |
69   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
70   | :c:member:`~PyTypeObject.tp_hash`              | :c:type:`hashfunc`                | __hash__          | X |   |   | G |
71   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
72   | :c:member:`~PyTypeObject.tp_call`              | :c:type:`ternaryfunc`             | __call__          |   | X |   | X |
73   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
74   | :c:member:`~PyTypeObject.tp_str`               | :c:type:`reprfunc`                | __str__           | X |   |   | X |
75   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
76   | :c:member:`~PyTypeObject.tp_getattro`          | :c:type:`getattrofunc`            | __getattribute__, | X | X |   | G |
77   |                                                |                                   | __getattr__       |   |   |   |   |
78   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
79   | :c:member:`~PyTypeObject.tp_setattro`          | :c:type:`setattrofunc`            | __setattr__,      | X | X |   | G |
80   |                                                |                                   | __delattr__       |   |   |   |   |
81   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
82   | :c:member:`~PyTypeObject.tp_as_buffer`         | :c:type:`PyBufferProcs` *         |                   |   |   |   | % |
83   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
84   | :c:member:`~PyTypeObject.tp_flags`             | unsigned long                     |                   | X | X |   | ? |
85   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
86   | :c:member:`~PyTypeObject.tp_doc`               | const char *                      | __doc__           | X | X |   |   |
87   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
88   | :c:member:`~PyTypeObject.tp_traverse`          | :c:type:`traverseproc`            |                   |   | X |   | G |
89   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
90   | :c:member:`~PyTypeObject.tp_clear`             | :c:type:`inquiry`                 |                   |   | X |   | G |
91   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
92   | :c:member:`~PyTypeObject.tp_richcompare`       | :c:type:`richcmpfunc`             | __lt__,           | X |   |   | G |
93   |                                                |                                   | __le__,           |   |   |   |   |
94   |                                                |                                   | __eq__,           |   |   |   |   |
95   |                                                |                                   | __ne__,           |   |   |   |   |
96   |                                                |                                   | __gt__,           |   |   |   |   |
97   |                                                |                                   | __ge__            |   |   |   |   |
98   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
99   | :c:member:`~PyTypeObject.tp_weaklistoffset`    | Py_ssize_t                        |                   |   | X |   | ? |
100   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
101   | :c:member:`~PyTypeObject.tp_iter`              | :c:type:`getiterfunc`             | __iter__          |   |   |   | X |
102   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
103   | :c:member:`~PyTypeObject.tp_iternext`          | :c:type:`iternextfunc`            | __next__          |   |   |   | X |
104   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
105   | :c:member:`~PyTypeObject.tp_methods`           | :c:type:`PyMethodDef` []          |                   | X | X |   |   |
106   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
107   | :c:member:`~PyTypeObject.tp_members`           | :c:type:`PyMemberDef` []          |                   |   | X |   |   |
108   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
109   | :c:member:`~PyTypeObject.tp_getset`            | :c:type:`PyGetSetDef` []          |                   | X | X |   |   |
110   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
111   | :c:member:`~PyTypeObject.tp_base`              | :c:type:`PyTypeObject` *          | __base__          |   |   | X |   |
112   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
113   | :c:member:`~PyTypeObject.tp_dict`              | :c:type:`PyObject` *              | __dict__          |   |   | ? |   |
114   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
115   | :c:member:`~PyTypeObject.tp_descr_get`         | :c:type:`descrgetfunc`            | __get__           |   |   |   | X |
116   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
117   | :c:member:`~PyTypeObject.tp_descr_set`         | :c:type:`descrsetfunc`            | __set__,          |   |   |   | X |
118   |                                                |                                   | __delete__        |   |   |   |   |
119   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
120   | :c:member:`~PyTypeObject.tp_dictoffset`        | Py_ssize_t                        |                   |   | X |   | ? |
121   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
122   | :c:member:`~PyTypeObject.tp_init`              | :c:type:`initproc`                | __init__          | X | X |   | X |
123   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
124   | :c:member:`~PyTypeObject.tp_alloc`             | :c:type:`allocfunc`               |                   | X |   | ? | ? |
125   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
126   | :c:member:`~PyTypeObject.tp_new`               | :c:type:`newfunc`                 | __new__           | X | X | ? | ? |
127   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
128   | :c:member:`~PyTypeObject.tp_free`              | :c:type:`freefunc`                |                   | X | X | ? | ? |
129   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
130   | :c:member:`~PyTypeObject.tp_is_gc`             | :c:type:`inquiry`                 |                   |   | X |   | X |
131   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
132   | <:c:member:`~PyTypeObject.tp_bases`>           | :c:type:`PyObject` *              | __bases__         |   |   | ~ |   |
133   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
134   | <:c:member:`~PyTypeObject.tp_mro`>             | :c:type:`PyObject` *              | __mro__           |   |   | ~ |   |
135   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
136   | [:c:member:`~PyTypeObject.tp_cache`]           | :c:type:`PyObject` *              |                   |   |   |       |
137   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
138   | [:c:member:`~PyTypeObject.tp_subclasses`]      | :c:type:`PyObject` *              | __subclasses__    |   |   |       |
139   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
140   | [:c:member:`~PyTypeObject.tp_weaklist`]        | :c:type:`PyObject` *              |                   |   |   |       |
141   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
142   | (:c:member:`~PyTypeObject.tp_del`)             | :c:type:`destructor`              |                   |   |   |   |   |
143   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
144   | [:c:member:`~PyTypeObject.tp_version_tag`]     | unsigned int                      |                   |   |   |       |
145   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
146   | :c:member:`~PyTypeObject.tp_finalize`          | :c:type:`destructor`              | __del__           |   |   |   | X |
147   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
148   | :c:member:`~PyTypeObject.tp_vectorcall`        | :c:type:`vectorcallfunc`          |                   |   |   |   |   |
149   +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+
150
151.. [#slots]
152   A slot name in parentheses indicates it is (effectively) deprecated.
153   Names in angle brackets should be treated as read-only.
154   Names in square brackets are for internal use only.
155   "<R>" (as a prefix) means the field is required (must be non-``NULL``).
156.. [#cols] Columns:
157
158   **"O"**:  set on :c:type:`PyBaseObject_Type`
159
160   **"T"**:  set on :c:type:`PyType_Type`
161
162   **"D"**:  default (if slot is set to ``NULL``)
163
164   .. code-block:: none
165
166      X - PyType_Ready sets this value if it is NULL
167      ~ - PyType_Ready always sets this value (it should be NULL)
168      ? - PyType_Ready may set this value depending on other slots
169
170      Also see the inheritance column ("I").
171
172   **"I"**:  inheritance
173
174   .. code-block:: none
175
176      X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
177      % - the slots of the sub-struct are inherited individually
178      G - inherited, but only in combination with other slots; see the slot's description
179      ? - it's complicated; see the slot's description
180
181   Note that some slots are effectively inherited through the normal
182   attribute lookup chain.
183
184.. _sub-slots:
185
186sub-slots
187^^^^^^^^^
188
189.. table::
190   :widths: 26,17,12
191
192   +---------------------------------------------------------+-----------------------------------+---------------+
193   | Slot                                                    | :ref:`Type <slot-typedefs-table>` | special       |
194   |                                                         |                                   | methods       |
195   +=========================================================+===================================+===============+
196   | :c:member:`~PyAsyncMethods.am_await`                    | :c:type:`unaryfunc`               | __await__     |
197   +---------------------------------------------------------+-----------------------------------+---------------+
198   | :c:member:`~PyAsyncMethods.am_aiter`                    | :c:type:`unaryfunc`               | __aiter__     |
199   +---------------------------------------------------------+-----------------------------------+---------------+
200   | :c:member:`~PyAsyncMethods.am_anext`                    | :c:type:`unaryfunc`               | __anext__     |
201   +---------------------------------------------------------+-----------------------------------+---------------+
202   | :c:member:`~PyAsyncMethods.am_send`                     | :c:type:`sendfunc`                |               |
203   +---------------------------------------------------------+-----------------------------------+---------------+
204   |                                                                                                             |
205   +---------------------------------------------------------+-----------------------------------+---------------+
206   | :c:member:`~PyNumberMethods.nb_add`                     | :c:type:`binaryfunc`              | __add__       |
207   |                                                         |                                   | __radd__      |
208   +---------------------------------------------------------+-----------------------------------+---------------+
209   | :c:member:`~PyNumberMethods.nb_inplace_add`             | :c:type:`binaryfunc`              | __iadd__      |
210   +---------------------------------------------------------+-----------------------------------+---------------+
211   | :c:member:`~PyNumberMethods.nb_subtract`                | :c:type:`binaryfunc`              | __sub__       |
212   |                                                         |                                   | __rsub__      |
213   +---------------------------------------------------------+-----------------------------------+---------------+
214   | :c:member:`~PyNumberMethods.nb_inplace_subtract`        | :c:type:`binaryfunc`              | __isub__      |
215   +---------------------------------------------------------+-----------------------------------+---------------+
216   | :c:member:`~PyNumberMethods.nb_multiply`                | :c:type:`binaryfunc`              | __mul__       |
217   |                                                         |                                   | __rmul__      |
218   +---------------------------------------------------------+-----------------------------------+---------------+
219   | :c:member:`~PyNumberMethods.nb_inplace_multiply`        | :c:type:`binaryfunc`              | __imul__      |
220   +---------------------------------------------------------+-----------------------------------+---------------+
221   | :c:member:`~PyNumberMethods.nb_remainder`               | :c:type:`binaryfunc`              | __mod__       |
222   |                                                         |                                   | __rmod__      |
223   +---------------------------------------------------------+-----------------------------------+---------------+
224   | :c:member:`~PyNumberMethods.nb_inplace_remainder`       | :c:type:`binaryfunc`              | __imod__      |
225   +---------------------------------------------------------+-----------------------------------+---------------+
226   | :c:member:`~PyNumberMethods.nb_divmod`                  | :c:type:`binaryfunc`              | __divmod__    |
227   |                                                         |                                   | __rdivmod__   |
228   +---------------------------------------------------------+-----------------------------------+---------------+
229   | :c:member:`~PyNumberMethods.nb_power`                   | :c:type:`ternaryfunc`             | __pow__       |
230   |                                                         |                                   | __rpow__      |
231   +---------------------------------------------------------+-----------------------------------+---------------+
232   | :c:member:`~PyNumberMethods.nb_inplace_power`           | :c:type:`ternaryfunc`             | __ipow__      |
233   +---------------------------------------------------------+-----------------------------------+---------------+
234   | :c:member:`~PyNumberMethods.nb_negative`                | :c:type:`unaryfunc`               | __neg__       |
235   +---------------------------------------------------------+-----------------------------------+---------------+
236   | :c:member:`~PyNumberMethods.nb_positive`                | :c:type:`unaryfunc`               | __pos__       |
237   +---------------------------------------------------------+-----------------------------------+---------------+
238   | :c:member:`~PyNumberMethods.nb_absolute`                | :c:type:`unaryfunc`               | __abs__       |
239   +---------------------------------------------------------+-----------------------------------+---------------+
240   | :c:member:`~PyNumberMethods.nb_bool`                    | :c:type:`inquiry`                 | __bool__      |
241   +---------------------------------------------------------+-----------------------------------+---------------+
242   | :c:member:`~PyNumberMethods.nb_invert`                  | :c:type:`unaryfunc`               | __invert__    |
243   +---------------------------------------------------------+-----------------------------------+---------------+
244   | :c:member:`~PyNumberMethods.nb_lshift`                  | :c:type:`binaryfunc`              | __lshift__    |
245   |                                                         |                                   | __rlshift__   |
246   +---------------------------------------------------------+-----------------------------------+---------------+
247   | :c:member:`~PyNumberMethods.nb_inplace_lshift`          | :c:type:`binaryfunc`              | __ilshift__   |
248   +---------------------------------------------------------+-----------------------------------+---------------+
249   | :c:member:`~PyNumberMethods.nb_rshift`                  | :c:type:`binaryfunc`              | __rshift__    |
250   |                                                         |                                   | __rrshift__   |
251   +---------------------------------------------------------+-----------------------------------+---------------+
252   | :c:member:`~PyNumberMethods.nb_inplace_rshift`          | :c:type:`binaryfunc`              | __irshift__   |
253   +---------------------------------------------------------+-----------------------------------+---------------+
254   | :c:member:`~PyNumberMethods.nb_and`                     | :c:type:`binaryfunc`              | __and__       |
255   |                                                         |                                   | __rand__      |
256   +---------------------------------------------------------+-----------------------------------+---------------+
257   | :c:member:`~PyNumberMethods.nb_inplace_and`             | :c:type:`binaryfunc`              | __iand__      |
258   +---------------------------------------------------------+-----------------------------------+---------------+
259   | :c:member:`~PyNumberMethods.nb_xor`                     | :c:type:`binaryfunc`              | __xor__       |
260   |                                                         |                                   | __rxor__      |
261   +---------------------------------------------------------+-----------------------------------+---------------+
262   | :c:member:`~PyNumberMethods.nb_inplace_xor`             | :c:type:`binaryfunc`              | __ixor__      |
263   +---------------------------------------------------------+-----------------------------------+---------------+
264   | :c:member:`~PyNumberMethods.nb_or`                      | :c:type:`binaryfunc`              | __or__        |
265   |                                                         |                                   | __ror__       |
266   +---------------------------------------------------------+-----------------------------------+---------------+
267   | :c:member:`~PyNumberMethods.nb_inplace_or`              | :c:type:`binaryfunc`              | __ior__       |
268   +---------------------------------------------------------+-----------------------------------+---------------+
269   | :c:member:`~PyNumberMethods.nb_int`                     | :c:type:`unaryfunc`               | __int__       |
270   +---------------------------------------------------------+-----------------------------------+---------------+
271   | :c:member:`~PyNumberMethods.nb_reserved`                | void *                            |               |
272   +---------------------------------------------------------+-----------------------------------+---------------+
273   | :c:member:`~PyNumberMethods.nb_float`                   | :c:type:`unaryfunc`               | __float__     |
274   +---------------------------------------------------------+-----------------------------------+---------------+
275   | :c:member:`~PyNumberMethods.nb_floor_divide`            | :c:type:`binaryfunc`              | __floordiv__  |
276   +---------------------------------------------------------+-----------------------------------+---------------+
277   | :c:member:`~PyNumberMethods.nb_inplace_floor_divide`    | :c:type:`binaryfunc`              | __ifloordiv__ |
278   +---------------------------------------------------------+-----------------------------------+---------------+
279   | :c:member:`~PyNumberMethods.nb_true_divide`             | :c:type:`binaryfunc`              | __truediv__   |
280   +---------------------------------------------------------+-----------------------------------+---------------+
281   | :c:member:`~PyNumberMethods.nb_inplace_true_divide`     | :c:type:`binaryfunc`              | __itruediv__  |
282   +---------------------------------------------------------+-----------------------------------+---------------+
283   | :c:member:`~PyNumberMethods.nb_index`                   | :c:type:`unaryfunc`               | __index__     |
284   +---------------------------------------------------------+-----------------------------------+---------------+
285   | :c:member:`~PyNumberMethods.nb_matrix_multiply`         | :c:type:`binaryfunc`              | __matmul__    |
286   |                                                         |                                   | __rmatmul__   |
287   +---------------------------------------------------------+-----------------------------------+---------------+
288   | :c:member:`~PyNumberMethods.nb_inplace_matrix_multiply` | :c:type:`binaryfunc`              | __imatmul__   |
289   +---------------------------------------------------------+-----------------------------------+---------------+
290   |                                                                                                             |
291   +---------------------------------------------------------+-----------------------------------+---------------+
292   | :c:member:`~PyMappingMethods.mp_length`                 | :c:type:`lenfunc`                 | __len__       |
293   +---------------------------------------------------------+-----------------------------------+---------------+
294   | :c:member:`~PyMappingMethods.mp_subscript`              | :c:type:`binaryfunc`              | __getitem__   |
295   +---------------------------------------------------------+-----------------------------------+---------------+
296   | :c:member:`~PyMappingMethods.mp_ass_subscript`          | :c:type:`objobjargproc`           | __setitem__,  |
297   |                                                         |                                   | __delitem__   |
298   +---------------------------------------------------------+-----------------------------------+---------------+
299   |                                                                                                             |
300   +---------------------------------------------------------+-----------------------------------+---------------+
301   | :c:member:`~PySequenceMethods.sq_length`                | :c:type:`lenfunc`                 | __len__       |
302   +---------------------------------------------------------+-----------------------------------+---------------+
303   | :c:member:`~PySequenceMethods.sq_concat`                | :c:type:`binaryfunc`              | __add__       |
304   +---------------------------------------------------------+-----------------------------------+---------------+
305   | :c:member:`~PySequenceMethods.sq_repeat`                | :c:type:`ssizeargfunc`            | __mul__       |
306   +---------------------------------------------------------+-----------------------------------+---------------+
307   | :c:member:`~PySequenceMethods.sq_item`                  | :c:type:`ssizeargfunc`            | __getitem__   |
308   +---------------------------------------------------------+-----------------------------------+---------------+
309   | :c:member:`~PySequenceMethods.sq_ass_item`              | :c:type:`ssizeobjargproc`         | __setitem__   |
310   |                                                         |                                   | __delitem__   |
311   +---------------------------------------------------------+-----------------------------------+---------------+
312   | :c:member:`~PySequenceMethods.sq_contains`              | :c:type:`objobjproc`              | __contains__  |
313   +---------------------------------------------------------+-----------------------------------+---------------+
314   | :c:member:`~PySequenceMethods.sq_inplace_concat`        | :c:type:`binaryfunc`              | __iadd__      |
315   +---------------------------------------------------------+-----------------------------------+---------------+
316   | :c:member:`~PySequenceMethods.sq_inplace_repeat`        | :c:type:`ssizeargfunc`            | __imul__      |
317   +---------------------------------------------------------+-----------------------------------+---------------+
318   |                                                                                                             |
319   +---------------------------------------------------------+-----------------------------------+---------------+
320   | :c:member:`~PyBufferProcs.bf_getbuffer`                 | :c:func:`getbufferproc`           |               |
321   +---------------------------------------------------------+-----------------------------------+---------------+
322   | :c:member:`~PyBufferProcs.bf_releasebuffer`             | :c:func:`releasebufferproc`       |               |
323   +---------------------------------------------------------+-----------------------------------+---------------+
324
325.. _slot-typedefs-table:
326
327slot typedefs
328^^^^^^^^^^^^^
329
330+-----------------------------+-----------------------------+----------------------+
331| typedef                     | Parameter Types             | Return Type          |
332+=============================+=============================+======================+
333| :c:type:`allocfunc`         | .. line-block::             | :c:type:`PyObject` * |
334|                             |                             |                      |
335|                             |    :c:type:`PyTypeObject` * |                      |
336|                             |    Py_ssize_t               |                      |
337+-----------------------------+-----------------------------+----------------------+
338| :c:type:`destructor`        | void *                      | void                 |
339+-----------------------------+-----------------------------+----------------------+
340| :c:type:`freefunc`          | void *                      | void                 |
341+-----------------------------+-----------------------------+----------------------+
342| :c:type:`traverseproc`      | .. line-block::             | int                  |
343|                             |                             |                      |
344|                             |    void *                   |                      |
345|                             |    :c:type:`visitproc`      |                      |
346|                             |    void *                   |                      |
347+-----------------------------+-----------------------------+----------------------+
348| :c:type:`newfunc`           | .. line-block::             | :c:type:`PyObject` * |
349|                             |                             |                      |
350|                             |    :c:type:`PyObject` *     |                      |
351|                             |    :c:type:`PyObject` *     |                      |
352|                             |    :c:type:`PyObject` *     |                      |
353+-----------------------------+-----------------------------+----------------------+
354| :c:type:`initproc`          | .. line-block::             | int                  |
355|                             |                             |                      |
356|                             |    :c:type:`PyObject` *     |                      |
357|                             |    :c:type:`PyObject` *     |                      |
358|                             |    :c:type:`PyObject` *     |                      |
359+-----------------------------+-----------------------------+----------------------+
360| :c:type:`reprfunc`          | :c:type:`PyObject` *        | :c:type:`PyObject` * |
361+-----------------------------+-----------------------------+----------------------+
362| :c:type:`getattrfunc`       | .. line-block::             | :c:type:`PyObject` * |
363|                             |                             |                      |
364|                             |    :c:type:`PyObject` *     |                      |
365|                             |    const char *             |                      |
366+-----------------------------+-----------------------------+----------------------+
367| :c:type:`setattrfunc`       | .. line-block::             | int                  |
368|                             |                             |                      |
369|                             |    :c:type:`PyObject` *     |                      |
370|                             |    const char *             |                      |
371|                             |    :c:type:`PyObject` *     |                      |
372+-----------------------------+-----------------------------+----------------------+
373| :c:type:`getattrofunc`      | .. line-block::             | :c:type:`PyObject` * |
374|                             |                             |                      |
375|                             |    :c:type:`PyObject` *     |                      |
376|                             |    :c:type:`PyObject` *     |                      |
377+-----------------------------+-----------------------------+----------------------+
378| :c:type:`setattrofunc`      | .. line-block::             | int                  |
379|                             |                             |                      |
380|                             |    :c:type:`PyObject` *     |                      |
381|                             |    :c:type:`PyObject` *     |                      |
382|                             |    :c:type:`PyObject` *     |                      |
383+-----------------------------+-----------------------------+----------------------+
384| :c:type:`descrgetfunc`      | .. line-block::             | :c:type:`PyObject` * |
385|                             |                             |                      |
386|                             |    :c:type:`PyObject` *     |                      |
387|                             |    :c:type:`PyObject` *     |                      |
388|                             |    :c:type:`PyObject` *     |                      |
389+-----------------------------+-----------------------------+----------------------+
390| :c:type:`descrsetfunc`      | .. line-block::             | int                  |
391|                             |                             |                      |
392|                             |    :c:type:`PyObject` *     |                      |
393|                             |    :c:type:`PyObject` *     |                      |
394|                             |    :c:type:`PyObject` *     |                      |
395+-----------------------------+-----------------------------+----------------------+
396| :c:type:`hashfunc`          | :c:type:`PyObject` *        | Py_hash_t            |
397+-----------------------------+-----------------------------+----------------------+
398| :c:type:`richcmpfunc`       | .. line-block::             | :c:type:`PyObject` * |
399|                             |                             |                      |
400|                             |    :c:type:`PyObject` *     |                      |
401|                             |    :c:type:`PyObject` *     |                      |
402|                             |    int                      |                      |
403+-----------------------------+-----------------------------+----------------------+
404| :c:type:`getiterfunc`       | :c:type:`PyObject` *        | :c:type:`PyObject` * |
405+-----------------------------+-----------------------------+----------------------+
406| :c:type:`iternextfunc`      | :c:type:`PyObject` *        | :c:type:`PyObject` * |
407+-----------------------------+-----------------------------+----------------------+
408| :c:type:`lenfunc`           | :c:type:`PyObject` *        | Py_ssize_t           |
409+-----------------------------+-----------------------------+----------------------+
410| :c:type:`getbufferproc`     | .. line-block::             | int                  |
411|                             |                             |                      |
412|                             |    :c:type:`PyObject` *     |                      |
413|                             |    :c:type:`Py_buffer` *    |                      |
414|                             |    int                      |                      |
415+-----------------------------+-----------------------------+----------------------+
416| :c:type:`releasebufferproc` | .. line-block::             | void                 |
417|                             |                             |                      |
418|                             |    :c:type:`PyObject` *     |                      |
419|                             |    :c:type:`Py_buffer` *    |                      |
420+-----------------------------+-----------------------------+----------------------+
421| :c:type:`inquiry`           | void *                      | int                  |
422+-----------------------------+-----------------------------+----------------------+
423| :c:type:`unaryfunc`         | .. line-block::             | :c:type:`PyObject` * |
424|                             |                             |                      |
425|                             |    :c:type:`PyObject` *     |                      |
426+-----------------------------+-----------------------------+----------------------+
427| :c:type:`binaryfunc`        | .. line-block::             | :c:type:`PyObject` * |
428|                             |                             |                      |
429|                             |    :c:type:`PyObject` *     |                      |
430|                             |    :c:type:`PyObject` *     |                      |
431+-----------------------------+-----------------------------+----------------------+
432| :c:type:`ternaryfunc`       | .. line-block::             | :c:type:`PyObject` * |
433|                             |                             |                      |
434|                             |    :c:type:`PyObject` *     |                      |
435|                             |    :c:type:`PyObject` *     |                      |
436|                             |    :c:type:`PyObject` *     |                      |
437+-----------------------------+-----------------------------+----------------------+
438| :c:type:`ssizeargfunc`      | .. line-block::             | :c:type:`PyObject` * |
439|                             |                             |                      |
440|                             |    :c:type:`PyObject` *     |                      |
441|                             |    Py_ssize_t               |                      |
442+-----------------------------+-----------------------------+----------------------+
443| :c:type:`ssizeobjargproc`   | .. line-block::             | int                  |
444|                             |                             |                      |
445|                             |    :c:type:`PyObject` *     |                      |
446|                             |    Py_ssize_t               |                      |
447+-----------------------------+-----------------------------+----------------------+
448| :c:type:`objobjproc`        | .. line-block::             | int                  |
449|                             |                             |                      |
450|                             |    :c:type:`PyObject` *     |                      |
451|                             |    :c:type:`PyObject` *     |                      |
452+-----------------------------+-----------------------------+----------------------+
453| :c:type:`objobjargproc`     | .. line-block::             | int                  |
454|                             |                             |                      |
455|                             |    :c:type:`PyObject` *     |                      |
456|                             |    :c:type:`PyObject` *     |                      |
457|                             |    :c:type:`PyObject` *     |                      |
458+-----------------------------+-----------------------------+----------------------+
459
460See :ref:`slot-typedefs` below for more detail.
461
462
463PyTypeObject Definition
464-----------------------
465
466The structure definition for :c:type:`PyTypeObject` can be found in
467:file:`Include/object.h`.  For convenience of reference, this repeats the
468definition found there:
469
470.. XXX Drop this?
471
472.. literalinclude:: ../includes/typestruct.h
473
474
475PyObject Slots
476--------------
477
478The type object structure extends the :c:type:`PyVarObject` structure. The
479:attr:`ob_size` field is used for dynamic types (created by  :func:`type_new`,
480usually called from a class statement). Note that :c:data:`PyType_Type` (the
481metatype) initializes :c:member:`~PyTypeObject.tp_itemsize`, which means that its instances (i.e.
482type objects) *must* have the :attr:`ob_size` field.
483
484
485.. c:member:: Py_ssize_t PyObject.ob_refcnt
486
487   This is the type object's reference count, initialized to ``1`` by the
488   ``PyObject_HEAD_INIT`` macro.  Note that for :ref:`statically allocated type
489   objects <static-types>`, the type's instances (objects whose :attr:`ob_type`
490   points back to the type) do *not* count as references.  But for
491   :ref:`dynamically allocated type objects <heap-types>`, the instances *do*
492   count as references.
493
494   **Inheritance:**
495
496   This field is not inherited by subtypes.
497
498
499.. c:member:: PyTypeObject* PyObject.ob_type
500
501   This is the type's type, in other words its metatype.  It is initialized by the
502   argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be
503   ``&PyType_Type``.  However, for dynamically loadable extension modules that must
504   be usable on Windows (at least), the compiler complains that this is not a valid
505   initializer.  Therefore, the convention is to pass ``NULL`` to the
506   ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the
507   start of the module's initialization function, before doing anything else.  This
508   is typically done like this::
509
510      Foo_Type.ob_type = &PyType_Type;
511
512   This should be done before any instances of the type are created.
513   :c:func:`PyType_Ready` checks if :attr:`ob_type` is ``NULL``, and if so,
514   initializes it to the :attr:`ob_type` field of the base class.
515   :c:func:`PyType_Ready` will not change this field if it is non-zero.
516
517   **Inheritance:**
518
519   This field is inherited by subtypes.
520
521
522.. c:member:: PyObject* PyObject._ob_next
523             PyObject* PyObject._ob_prev
524
525   These fields are only present when the macro ``Py_TRACE_REFS`` is defined
526   (see the :option:`configure --with-trace-refs option <--with-trace-refs>`).
527
528   Their initialization to ``NULL`` is taken care of by the
529   ``PyObject_HEAD_INIT`` macro.  For :ref:`statically allocated objects
530   <static-types>`, these fields always remain ``NULL``.  For :ref:`dynamically
531   allocated objects <heap-types>`, these two fields are used to link the
532   object into a doubly-linked list of *all* live objects on the heap.
533
534   This could be used for various debugging purposes; currently the only uses
535   are the :func:`sys.getobjects` function and to print the objects that are
536   still alive at the end of a run when the environment variable
537   :envvar:`PYTHONDUMPREFS` is set.
538
539   **Inheritance:**
540
541   These fields are not inherited by subtypes.
542
543
544PyVarObject Slots
545-----------------
546
547.. c:member:: Py_ssize_t PyVarObject.ob_size
548
549   For :ref:`statically allocated type objects <static-types>`, this should be
550   initialized to zero. For :ref:`dynamically allocated type objects
551   <heap-types>`, this field has a special internal meaning.
552
553   **Inheritance:**
554
555   This field is not inherited by subtypes.
556
557
558PyTypeObject Slots
559------------------
560
561Each slot has a section describing inheritance.  If :c:func:`PyType_Ready`
562may set a value when the field is set to ``NULL`` then there will also be
563a "Default" section.  (Note that many fields set on :c:type:`PyBaseObject_Type`
564and :c:type:`PyType_Type` effectively act as defaults.)
565
566.. c:member:: const char* PyTypeObject.tp_name
567
568   Pointer to a NUL-terminated string containing the name of the type. For types
569   that are accessible as module globals, the string should be the full module
570   name, followed by a dot, followed by the type name; for built-in types, it
571   should be just the type name.  If the module is a submodule of a package, the
572   full package name is part of the full module name.  For example, a type named
573   :class:`T` defined in module :mod:`M` in subpackage :mod:`Q` in package :mod:`P`
574   should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``.
575
576   For :ref:`dynamically allocated type objects <heap-types>`,
577   this should just be the type name, and
578   the module name explicitly stored in the type dict as the value for key
579   ``'__module__'``.
580
581   For :ref:`statically allocated type objects <static-types>`,
582   the *tp_name* field should contain a dot.
583   Everything before the last dot is made accessible as the :attr:`__module__`
584   attribute, and everything after the last dot is made accessible as the
585   :attr:`~definition.__name__` attribute.
586
587   If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the
588   :attr:`~definition.__name__` attribute, and the :attr:`__module__` attribute is undefined
589   (unless explicitly set in the dictionary, as explained above).  This means your
590   type will be impossible to pickle.  Additionally, it will not be listed in
591   module documentations created with pydoc.
592
593   This field must not be ``NULL``.  It is the only required field
594   in :c:func:`PyTypeObject` (other than potentially
595   :c:member:`~PyTypeObject.tp_itemsize`).
596
597   **Inheritance:**
598
599   This field is not inherited by subtypes.
600
601
602.. c:member:: Py_ssize_t PyTypeObject.tp_basicsize
603             Py_ssize_t PyTypeObject.tp_itemsize
604
605   These fields allow calculating the size in bytes of instances of the type.
606
607   There are two kinds of types: types with fixed-length instances have a zero
608   :c:member:`~PyTypeObject.tp_itemsize` field, types with variable-length instances have a non-zero
609   :c:member:`~PyTypeObject.tp_itemsize` field.  For a type with fixed-length instances, all
610   instances have the same size, given in :c:member:`~PyTypeObject.tp_basicsize`.
611
612   For a type with variable-length instances, the instances must have an
613   :attr:`ob_size` field, and the instance size is :c:member:`~PyTypeObject.tp_basicsize` plus N
614   times :c:member:`~PyTypeObject.tp_itemsize`, where N is the "length" of the object.  The value of
615   N is typically stored in the instance's :attr:`ob_size` field.  There are
616   exceptions:  for example, ints use a negative :attr:`ob_size` to indicate a
617   negative number, and N is ``abs(ob_size)`` there.  Also, the presence of an
618   :attr:`ob_size` field in the instance layout doesn't mean that the instance
619   structure is variable-length (for example, the structure for the list type has
620   fixed-length instances, yet those instances have a meaningful :attr:`ob_size`
621   field).
622
623   The basic size includes the fields in the instance declared by the macro
624   :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to
625   declare the instance struct) and this in turn includes the :attr:`_ob_prev` and
626   :attr:`_ob_next` fields if they are present.  This means that the only correct
627   way to get an initializer for the :c:member:`~PyTypeObject.tp_basicsize` is to use the
628   ``sizeof`` operator on the struct used to declare the instance layout.
629   The basic size does not include the GC header size.
630
631   A note about alignment: if the variable items require a particular alignment,
632   this should be taken care of by the value of :c:member:`~PyTypeObject.tp_basicsize`.  Example:
633   suppose a type implements an array of ``double``. :c:member:`~PyTypeObject.tp_itemsize` is
634   ``sizeof(double)``. It is the programmer's responsibility that
635   :c:member:`~PyTypeObject.tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the
636   alignment requirement for ``double``).
637
638   For any type with variable-length instances, this field must not be ``NULL``.
639
640   **Inheritance:**
641
642   These fields are inherited separately by subtypes.  If the base type has a
643   non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to set
644   :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a subtype (though this
645   depends on the implementation of the base type).
646
647
648.. c:member:: destructor PyTypeObject.tp_dealloc
649
650   A pointer to the instance destructor function.  This function must be defined
651   unless the type guarantees that its instances will never be deallocated (as is
652   the case for the singletons ``None`` and ``Ellipsis``).  The function signature is::
653
654      void tp_dealloc(PyObject *self);
655
656   The destructor function is called by the :c:func:`Py_DECREF` and
657   :c:func:`Py_XDECREF` macros when the new reference count is zero.  At this point,
658   the instance is still in existence, but there are no references to it.  The
659   destructor function should free all references which the instance owns, free all
660   memory buffers owned by the instance (using the freeing function corresponding
661   to the allocation function used to allocate the buffer), and call the type's
662   :c:member:`~PyTypeObject.tp_free` function.  If the type is not subtypable
663   (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is
664   permissible to call the object deallocator directly instead of via
665   :c:member:`~PyTypeObject.tp_free`.  The object deallocator should be the one used to allocate the
666   instance; this is normally :c:func:`PyObject_Del` if the instance was allocated
667   using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or
668   :c:func:`PyObject_GC_Del` if the instance was allocated using
669   :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`.
670
671   If the type supports garbage collection (has the :const:`Py_TPFLAGS_HAVE_GC`
672   flag bit set), the destructor should call :c:func:`PyObject_GC_UnTrack`
673   before clearing any member fields.
674
675   .. code-block:: c
676
677     static void foo_dealloc(foo_object *self) {
678         PyObject_GC_UnTrack(self);
679         Py_CLEAR(self->ref);
680         Py_TYPE(self)->tp_free((PyObject *)self);
681     }
682
683   Finally, if the type is heap allocated (:const:`Py_TPFLAGS_HEAPTYPE`), the
684   deallocator should decrement the reference count for its type object after
685   calling the type deallocator. In order to avoid dangling pointers, the
686   recommended way to achieve this is:
687
688   .. code-block:: c
689
690     static void foo_dealloc(foo_object *self) {
691         PyTypeObject *tp = Py_TYPE(self);
692         // free references and buffers here
693         tp->tp_free(self);
694         Py_DECREF(tp);
695     }
696
697
698   **Inheritance:**
699
700   This field is inherited by subtypes.
701
702
703.. c:member:: Py_ssize_t PyTypeObject.tp_vectorcall_offset
704
705   An optional offset to a per-instance function that implements calling
706   the object using the :ref:`vectorcall protocol <vectorcall>`,
707   a more efficient alternative
708   of the simpler :c:member:`~PyTypeObject.tp_call`.
709
710   This field is only used if the flag :const:`Py_TPFLAGS_HAVE_VECTORCALL`
711   is set. If so, this must be a positive integer containing the offset in the
712   instance of a :c:type:`vectorcallfunc` pointer.
713
714   The *vectorcallfunc* pointer may be ``NULL``, in which case the instance behaves
715   as if :const:`Py_TPFLAGS_HAVE_VECTORCALL` was not set: calling the instance
716   falls back to :c:member:`~PyTypeObject.tp_call`.
717
718   Any class that sets ``Py_TPFLAGS_HAVE_VECTORCALL`` must also set
719   :c:member:`~PyTypeObject.tp_call` and make sure its behaviour is consistent
720   with the *vectorcallfunc* function.
721   This can be done by setting *tp_call* to :c:func:`PyVectorcall_Call`.
722
723   .. warning::
724
725      It is not recommended for :ref:`heap types <heap-types>` to implement
726      the vectorcall protocol.
727      When a user sets :attr:`__call__` in Python code, only *tp_call* is updated,
728      likely making it inconsistent with the vectorcall function.
729
730   .. note::
731
732      The semantics of the ``tp_vectorcall_offset`` slot are provisional and
733      expected to be finalized in Python 3.9.
734      If you use vectorcall, plan for updating your code for Python 3.9.
735
736   .. versionchanged:: 3.8
737
738      Before version 3.8, this slot was named ``tp_print``.
739      In Python 2.x, it was used for printing to a file.
740      In Python 3.0 to 3.7, it was unused.
741
742   **Inheritance:**
743
744   This field is always inherited.
745   However, the :const:`Py_TPFLAGS_HAVE_VECTORCALL` flag is not
746   always inherited. If it's not, then the subclass won't use
747   :ref:`vectorcall <vectorcall>`, except when
748   :c:func:`PyVectorcall_Call` is explicitly called.
749   This is in particular the case for :ref:`heap types <heap-types>`
750   (including subclasses defined in Python).
751
752
753.. c:member:: getattrfunc PyTypeObject.tp_getattr
754
755   An optional pointer to the get-attribute-string function.
756
757   This field is deprecated.  When it is defined, it should point to a function
758   that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string
759   instead of a Python string object to give the attribute name.
760
761   **Inheritance:**
762
763   Group: :attr:`tp_getattr`, :attr:`tp_getattro`
764
765   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype
766   inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
767   the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``.
768
769
770.. c:member:: setattrfunc PyTypeObject.tp_setattr
771
772   An optional pointer to the function for setting and deleting attributes.
773
774   This field is deprecated.  When it is defined, it should point to a function
775   that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string
776   instead of a Python string object to give the attribute name.
777
778   **Inheritance:**
779
780   Group: :attr:`tp_setattr`, :attr:`tp_setattro`
781
782   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype
783   inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
784   the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``.
785
786
787.. c:member:: PyAsyncMethods* PyTypeObject.tp_as_async
788
789   Pointer to an additional structure that contains fields relevant only to
790   objects which implement :term:`awaitable` and :term:`asynchronous iterator`
791   protocols at the C-level.  See :ref:`async-structs` for details.
792
793   .. versionadded:: 3.5
794      Formerly known as ``tp_compare`` and ``tp_reserved``.
795
796   **Inheritance:**
797
798   The :c:member:`~PyTypeObject.tp_as_async` field is not inherited,
799   but the contained fields are inherited individually.
800
801
802.. c:member:: reprfunc PyTypeObject.tp_repr
803
804   .. index:: builtin: repr
805
806   An optional pointer to a function that implements the built-in function
807   :func:`repr`.
808
809   The signature is the same as for :c:func:`PyObject_Repr`::
810
811      PyObject *tp_repr(PyObject *self);
812
813   The function must return a string or a Unicode object.  Ideally,
814   this function should return a string that, when passed to
815   :func:`eval`, given a suitable environment, returns an object with the
816   same value.  If this is not feasible, it should return a string starting with
817   ``'<'`` and ending with ``'>'`` from which both the type and the value of the
818   object can be deduced.
819
820   **Inheritance:**
821
822   This field is inherited by subtypes.
823
824   **Default:**
825
826   When this field is not set, a string of the form ``<%s object at %p>`` is
827   returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's
828   memory address.
829
830
831.. c:member:: PyNumberMethods* PyTypeObject.tp_as_number
832
833   Pointer to an additional structure that contains fields relevant only to
834   objects which implement the number protocol.  These fields are documented in
835   :ref:`number-structs`.
836
837   **Inheritance:**
838
839   The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the contained fields are
840   inherited individually.
841
842
843.. c:member:: PySequenceMethods* PyTypeObject.tp_as_sequence
844
845   Pointer to an additional structure that contains fields relevant only to
846   objects which implement the sequence protocol.  These fields are documented
847   in :ref:`sequence-structs`.
848
849   **Inheritance:**
850
851   The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the contained fields
852   are inherited individually.
853
854
855.. c:member:: PyMappingMethods* PyTypeObject.tp_as_mapping
856
857   Pointer to an additional structure that contains fields relevant only to
858   objects which implement the mapping protocol.  These fields are documented in
859   :ref:`mapping-structs`.
860
861   **Inheritance:**
862
863   The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the contained fields
864   are inherited individually.
865
866
867.. c:member:: hashfunc PyTypeObject.tp_hash
868
869   .. index:: builtin: hash
870
871   An optional pointer to a function that implements the built-in function
872   :func:`hash`.
873
874   The signature is the same as for :c:func:`PyObject_Hash`::
875
876      Py_hash_t tp_hash(PyObject *);
877
878   The value ``-1`` should not be returned as a
879   normal return value; when an error occurs during the computation of the hash
880   value, the function should set an exception and return ``-1``.
881
882   When this field is not set (*and* :attr:`tp_richcompare` is not set),
883   an attempt to take the hash of the object raises :exc:`TypeError`.
884   This is the same as setting it to :c:func:`PyObject_HashNotImplemented`.
885
886   This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to
887   block inheritance of the hash method from a parent type. This is interpreted
888   as the equivalent of ``__hash__ = None`` at the Python level, causing
889   ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note
890   that the converse is also true - setting ``__hash__ = None`` on a class at
891   the Python level will result in the ``tp_hash`` slot being set to
892   :c:func:`PyObject_HashNotImplemented`.
893
894   **Inheritance:**
895
896   Group: :attr:`tp_hash`, :attr:`tp_richcompare`
897
898   This field is inherited by subtypes together with
899   :c:member:`~PyTypeObject.tp_richcompare`: a subtype inherits both of
900   :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
901   :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``.
902
903
904.. c:member:: ternaryfunc PyTypeObject.tp_call
905
906   An optional pointer to a function that implements calling the object.  This
907   should be ``NULL`` if the object is not callable.  The signature is the same as
908   for :c:func:`PyObject_Call`::
909
910      PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);
911
912   **Inheritance:**
913
914   This field is inherited by subtypes.
915
916
917.. c:member:: reprfunc PyTypeObject.tp_str
918
919   An optional pointer to a function that implements the built-in operation
920   :func:`str`.  (Note that :class:`str` is a type now, and :func:`str` calls the
921   constructor for that type.  This constructor calls :c:func:`PyObject_Str` to do
922   the actual work, and :c:func:`PyObject_Str` will call this handler.)
923
924   The signature is the same as for :c:func:`PyObject_Str`::
925
926      PyObject *tp_str(PyObject *self);
927
928   The function must return a string or a Unicode object.  It should be a "friendly" string
929   representation of the object, as this is the representation that will be used,
930   among other things, by the :func:`print` function.
931
932   **Inheritance:**
933
934   This field is inherited by subtypes.
935
936   **Default:**
937
938   When this field is not set, :c:func:`PyObject_Repr` is called to return a string
939   representation.
940
941
942.. c:member:: getattrofunc PyTypeObject.tp_getattro
943
944   An optional pointer to the get-attribute function.
945
946   The signature is the same as for :c:func:`PyObject_GetAttr`::
947
948      PyObject *tp_getattro(PyObject *self, PyObject *attr);
949
950   It is usually convenient to set this field to :c:func:`PyObject_GenericGetAttr`,
951   which implements the normal way of looking for object attributes.
952
953   **Inheritance:**
954
955   Group: :attr:`tp_getattr`, :attr:`tp_getattro`
956
957   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattr`: a subtype
958   inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
959   the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``.
960
961   **Default:**
962
963   :c:type:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`.
964
965
966.. c:member:: setattrofunc PyTypeObject.tp_setattro
967
968   An optional pointer to the function for setting and deleting attributes.
969
970   The signature is the same as for :c:func:`PyObject_SetAttr`::
971
972      int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
973
974   In addition, setting *value* to ``NULL`` to delete an attribute must be
975   supported.  It is usually convenient to set this field to
976   :c:func:`PyObject_GenericSetAttr`, which implements the normal
977   way of setting object attributes.
978
979   **Inheritance:**
980
981   Group: :attr:`tp_setattr`, :attr:`tp_setattro`
982
983   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattr`: a subtype
984   inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
985   the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``.
986
987   **Default:**
988
989   :c:type:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`.
990
991
992.. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer
993
994   Pointer to an additional structure that contains fields relevant only to objects
995   which implement the buffer interface.  These fields are documented in
996   :ref:`buffer-structs`.
997
998   **Inheritance:**
999
1000   The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited,
1001   but the contained fields are inherited individually.
1002
1003
1004.. c:member:: unsigned long PyTypeObject.tp_flags
1005
1006   This field is a bit mask of various flags.  Some flags indicate variant
1007   semantics for certain situations; others are used to indicate that certain
1008   fields in the type object (or in the extension structures referenced via
1009   :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and
1010   :c:member:`~PyTypeObject.tp_as_buffer`) that were historically not always present are valid; if
1011   such a flag bit is clear, the type fields it guards must not be accessed and
1012   must be considered to have a zero or ``NULL`` value instead.
1013
1014   **Inheritance:**
1015
1016   Inheritance of this field is complicated.  Most flag bits are inherited
1017   individually, i.e. if the base type has a flag bit set, the subtype inherits
1018   this flag bit.  The flag bits that pertain to extension structures are strictly
1019   inherited if the extension structure is inherited, i.e. the base type's value of
1020   the flag bit is copied into the subtype together with a pointer to the extension
1021   structure.  The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with
1022   the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the
1023   :const:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the
1024   :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have
1025   ``NULL`` values.
1026
1027   .. XXX are most flag bits *really* inherited individually?
1028
1029   **Default:**
1030
1031   :c:type:`PyBaseObject_Type` uses
1032   ``Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE``.
1033
1034   **Bit Masks:**
1035
1036   The following bit masks are currently defined; these can be ORed together using
1037   the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field.  The macro
1038   :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
1039   checks whether ``tp->tp_flags & f`` is non-zero.
1040
1041   .. data:: Py_TPFLAGS_HEAPTYPE
1042
1043      This bit is set when the type object itself is allocated on the heap, for
1044      example, types created dynamically using :c:func:`PyType_FromSpec`.  In this
1045      case, the :attr:`ob_type` field of its instances is considered a reference to
1046      the type, and the type object is INCREF'ed when a new instance is created, and
1047      DECREF'ed when an instance is destroyed (this does not apply to instances of
1048      subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
1049      DECREF'ed).
1050
1051      **Inheritance:**
1052
1053      ???
1054
1055
1056   .. data:: Py_TPFLAGS_BASETYPE
1057
1058      This bit is set when the type can be used as the base type of another type.  If
1059      this bit is clear, the type cannot be subtyped (similar to a "final" class in
1060      Java).
1061
1062      **Inheritance:**
1063
1064      ???
1065
1066
1067   .. data:: Py_TPFLAGS_READY
1068
1069      This bit is set when the type object has been fully initialized by
1070      :c:func:`PyType_Ready`.
1071
1072      **Inheritance:**
1073
1074      ???
1075
1076
1077   .. data:: Py_TPFLAGS_READYING
1078
1079      This bit is set while :c:func:`PyType_Ready` is in the process of initializing
1080      the type object.
1081
1082      **Inheritance:**
1083
1084      ???
1085
1086
1087   .. data:: Py_TPFLAGS_HAVE_GC
1088
1089      This bit is set when the object supports garbage collection.  If this bit
1090      is set, instances must be created using :c:func:`PyObject_GC_New` and
1091      destroyed using :c:func:`PyObject_GC_Del`.  More information in section
1092      :ref:`supporting-cycle-detection`.  This bit also implies that the
1093      GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in
1094      the type object.
1095
1096      **Inheritance:**
1097
1098      Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear`
1099
1100      The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited
1101      together with the :attr:`tp_traverse` and :attr:`tp_clear`
1102      fields, i.e.  if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is
1103      clear in the subtype and the :attr:`tp_traverse` and
1104      :attr:`tp_clear` fields in the subtype exist and have ``NULL``
1105      values.
1106
1107
1108   .. data:: Py_TPFLAGS_DEFAULT
1109
1110      This is a bitmask of all the bits that pertain to the existence of certain
1111      fields in the type object and its extension structures. Currently, it includes
1112      the following bits: :const:`Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`.
1113
1114      **Inheritance:**
1115
1116      ???
1117
1118
1119   .. data:: Py_TPFLAGS_METHOD_DESCRIPTOR
1120
1121      This bit indicates that objects behave like unbound methods.
1122
1123      If this flag is set for ``type(meth)``, then:
1124
1125      - ``meth.__get__(obj, cls)(*args, **kwds)`` (with ``obj`` not None)
1126        must be equivalent to ``meth(obj, *args, **kwds)``.
1127
1128      - ``meth.__get__(None, cls)(*args, **kwds)``
1129        must be equivalent to ``meth(*args, **kwds)``.
1130
1131      This flag enables an optimization for typical method calls like
1132      ``obj.meth()``: it avoids creating a temporary "bound method" object for
1133      ``obj.meth``.
1134
1135      .. versionadded:: 3.8
1136
1137      **Inheritance:**
1138
1139      This flag is never inherited by :ref:`heap types <heap-types>`.
1140      For extension types, it is inherited whenever
1141      :c:member:`~PyTypeObject.tp_descr_get` is inherited.
1142
1143
1144   .. XXX Document more flags here?
1145
1146
1147   .. data:: Py_TPFLAGS_LONG_SUBCLASS
1148   .. data:: Py_TPFLAGS_LIST_SUBCLASS
1149   .. data:: Py_TPFLAGS_TUPLE_SUBCLASS
1150   .. data:: Py_TPFLAGS_BYTES_SUBCLASS
1151   .. data:: Py_TPFLAGS_UNICODE_SUBCLASS
1152   .. data:: Py_TPFLAGS_DICT_SUBCLASS
1153   .. data:: Py_TPFLAGS_BASE_EXC_SUBCLASS
1154   .. data:: Py_TPFLAGS_TYPE_SUBCLASS
1155
1156      These flags are used by functions such as
1157      :c:func:`PyLong_Check` to quickly determine if a type is a subclass
1158      of a built-in type; such specific checks are faster than a generic
1159      check, like :c:func:`PyObject_IsInstance`. Custom types that inherit
1160      from built-ins should have their :c:member:`~PyTypeObject.tp_flags`
1161      set appropriately, or the code that interacts with such types
1162      will behave differently depending on what kind of check is used.
1163
1164
1165   .. data:: Py_TPFLAGS_HAVE_FINALIZE
1166
1167      This bit is set when the :c:member:`~PyTypeObject.tp_finalize` slot is present in the
1168      type structure.
1169
1170      .. versionadded:: 3.4
1171
1172      .. deprecated:: 3.8
1173         This flag isn't necessary anymore, as the interpreter assumes the
1174         :c:member:`~PyTypeObject.tp_finalize` slot is always present in the
1175         type structure.
1176
1177
1178   .. data:: Py_TPFLAGS_HAVE_VECTORCALL
1179
1180      This bit is set when the class implements
1181      the :ref:`vectorcall protocol <vectorcall>`.
1182      See :c:member:`~PyTypeObject.tp_vectorcall_offset` for details.
1183
1184      **Inheritance:**
1185
1186      This bit is inherited for :ref:`static subtypes <static-types>` if
1187      :c:member:`~PyTypeObject.tp_call` is also inherited.
1188      :ref:`Heap types <heap-types>` do not inherit ``Py_TPFLAGS_HAVE_VECTORCALL``.
1189
1190      .. versionadded:: 3.9
1191
1192   .. data:: Py_TPFLAGS_IMMUTABLETYPE
1193
1194      This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.
1195
1196      :c:func:`PyType_Ready` automatically applies this flag to
1197      :ref:`static types <static-types>`.
1198
1199      **Inheritance:**
1200
1201      This flag is not inherited.
1202
1203      .. versionadded:: 3.10
1204
1205   .. data:: Py_TPFLAGS_DISALLOW_INSTANTIATION
1206
1207      Disallow creating instances of the type: set
1208      :c:member:`~PyTypeObject.tp_new` to NULL and don't create the ``__new__``
1209      key in the type dictionary.
1210
1211      The flag must be set before creating the type, not after. For example, it
1212      must be set before :c:func:`PyType_Ready` is called on the type.
1213
1214      The flag is set automatically on :ref:`static types <static-types>` if
1215      :c:member:`~PyTypeObject.tp_base` is NULL or ``&PyBaseObject_Type`` and
1216      :c:member:`~PyTypeObject.tp_new` is NULL.
1217
1218      **Inheritance:**
1219
1220      This flag is not inherited.
1221
1222      .. versionadded:: 3.10
1223
1224
1225   .. data:: Py_TPFLAGS_MAPPING
1226
1227      This bit indicates that instances of the class may match mapping patterns
1228      when used as the subject of a :keyword:`match` block. It is automatically
1229      set when registering or subclassing :class:`collections.abc.Mapping`, and
1230      unset when registering :class:`collections.abc.Sequence`.
1231
1232      .. note::
1233
1234         :const:`Py_TPFLAGS_MAPPING` and :const:`Py_TPFLAGS_SEQUENCE` are
1235         mutually exclusive; it is an error enable both flags simultaneously.
1236
1237      **Inheritance:**
1238
1239      This flag is inherited by types that do not already set
1240      :const:`Py_TPFLAGS_SEQUENCE`.
1241
1242      .. seealso:: :pep:`634` -- Structural Pattern Matching: Specification
1243
1244      .. versionadded:: 3.10
1245
1246
1247   .. data:: Py_TPFLAGS_SEQUENCE
1248
1249      This bit indicates that instances of the class may match sequence patterns
1250      when used as the subject of a :keyword:`match` block. It is automatically
1251      set when registering or subclassing :class:`collections.abc.Sequence`, and
1252      unset when registering :class:`collections.abc.Mapping`.
1253
1254      .. note::
1255
1256         :const:`Py_TPFLAGS_MAPPING` and :const:`Py_TPFLAGS_SEQUENCE` are
1257         mutually exclusive; it is an error enable both flags simultaneously.
1258
1259      **Inheritance:**
1260
1261      This flag is inherited by types that do not already set
1262      :const:`Py_TPFLAGS_MAPPING`.
1263
1264      .. seealso:: :pep:`634` -- Structural Pattern Matching: Specification
1265
1266      .. versionadded:: 3.10
1267
1268
1269.. c:member:: const char* PyTypeObject.tp_doc
1270
1271   An optional pointer to a NUL-terminated C string giving the docstring for this
1272   type object.  This is exposed as the :attr:`__doc__` attribute on the type and
1273   instances of the type.
1274
1275   **Inheritance:**
1276
1277   This field is *not* inherited by subtypes.
1278
1279
1280.. c:member:: traverseproc PyTypeObject.tp_traverse
1281
1282   An optional pointer to a traversal function for the garbage collector.  This is
1283   only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.  The signature is::
1284
1285      int tp_traverse(PyObject *self, visitproc visit, void *arg);
1286
1287   More information about Python's garbage collection scheme can be found
1288   in section :ref:`supporting-cycle-detection`.
1289
1290   The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
1291   reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
1292   simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
1293   objects that the instance owns. For example, this is function :c:func:`local_traverse` from the
1294   :mod:`_thread` extension module::
1295
1296      static int
1297      local_traverse(localobject *self, visitproc visit, void *arg)
1298      {
1299          Py_VISIT(self->args);
1300          Py_VISIT(self->kw);
1301          Py_VISIT(self->dict);
1302          return 0;
1303      }
1304
1305   Note that :c:func:`Py_VISIT` is called only on those members that can participate
1306   in reference cycles.  Although there is also a ``self->key`` member, it can only
1307   be ``NULL`` or a Python string and therefore cannot be part of a reference cycle.
1308
1309   On the other hand, even if you know a member can never be part of a cycle, as a
1310   debugging aid you may want to visit it anyway just so the :mod:`gc` module's
1311   :func:`~gc.get_referents` function will include it.
1312
1313   .. warning::
1314       When implementing :c:member:`~PyTypeObject.tp_traverse`, only the
1315       members that the instance *owns* (by having :term:`strong references
1316       <strong reference>` to them) must be
1317       visited. For instance, if an object supports weak references via the
1318       :c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
1319       the linked list (what *tp_weaklist* points to) must **not** be
1320       visited as the instance does not directly own the weak references to itself
1321       (the weakreference list is there to support the weak reference machinery,
1322       but the instance has no strong reference to the elements inside it, as they
1323       are allowed to be removed even if the instance is still alive).
1324
1325   Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
1326   :c:func:`local_traverse` to have these specific names; don't name them just
1327   anything.
1328
1329   Instances of :ref:`heap-allocated types <heap-types>` hold a reference to
1330   their type. Their traversal function must therefore either visit
1331   :c:func:`Py_TYPE(self) <Py_TYPE>`, or delegate this responsibility by
1332   calling ``tp_traverse`` of another heap-allocated type (such as a
1333   heap-allocated superclass).
1334   If they do not, the type object may not be garbage-collected.
1335
1336   .. versionchanged:: 3.9
1337
1338      Heap-allocated types are expected to visit ``Py_TYPE(self)`` in
1339      ``tp_traverse``.  In earlier versions of Python, due to
1340      `bug 40217 <https://bugs.python.org/issue40217>`_, doing this
1341      may lead to crashes in subclasses.
1342
1343   **Inheritance:**
1344
1345   Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear`
1346
1347   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_clear` and the
1348   :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
1349   :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
1350   the subtype.
1351
1352
1353.. c:member:: inquiry PyTypeObject.tp_clear
1354
1355   An optional pointer to a clear function for the garbage collector. This is only
1356   used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.  The signature is::
1357
1358      int tp_clear(PyObject *);
1359
1360   The :c:member:`~PyTypeObject.tp_clear` member function is used to break reference cycles in cyclic
1361   garbage detected by the garbage collector.  Taken together, all :c:member:`~PyTypeObject.tp_clear`
1362   functions in the system must combine to break all reference cycles.  This is
1363   subtle, and if in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function.  For example,
1364   the tuple type does not implement a :c:member:`~PyTypeObject.tp_clear` function, because it's
1365   possible to prove that no reference cycle can be composed entirely of tuples.
1366   Therefore the :c:member:`~PyTypeObject.tp_clear` functions of other types must be sufficient to
1367   break any cycle containing a tuple.  This isn't immediately obvious, and there's
1368   rarely a good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`.
1369
1370   Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the instance's references to
1371   those of its members that may be Python objects, and set its pointers to those
1372   members to ``NULL``, as in the following example::
1373
1374      static int
1375      local_clear(localobject *self)
1376      {
1377          Py_CLEAR(self->key);
1378          Py_CLEAR(self->args);
1379          Py_CLEAR(self->kw);
1380          Py_CLEAR(self->dict);
1381          return 0;
1382      }
1383
1384   The :c:func:`Py_CLEAR` macro should be used, because clearing references is
1385   delicate:  the reference to the contained object must not be decremented until
1386   after the pointer to the contained object is set to ``NULL``.  This is because
1387   decrementing the reference count may cause the contained object to become trash,
1388   triggering a chain of reclamation activity that may include invoking arbitrary
1389   Python code (due to finalizers, or weakref callbacks, associated with the
1390   contained object). If it's possible for such code to reference *self* again,
1391   it's important that the pointer to the contained object be ``NULL`` at that time,
1392   so that *self* knows the contained object can no longer be used.  The
1393   :c:func:`Py_CLEAR` macro performs the operations in a safe order.
1394
1395   Note that :c:member:`~PyTypeObject.tp_clear` is not *always* called
1396   before an instance is deallocated. For example, when reference counting
1397   is enough to determine that an object is no longer used, the cyclic garbage
1398   collector is not involved and :c:member:`~PyTypeObject.tp_dealloc` is
1399   called directly.
1400
1401   Because the goal of :c:member:`~PyTypeObject.tp_clear` functions is to break reference cycles,
1402   it's not necessary to clear contained objects like Python strings or Python
1403   integers, which can't participate in reference cycles. On the other hand, it may
1404   be convenient to clear all contained Python objects, and write the type's
1405   :c:member:`~PyTypeObject.tp_dealloc` function to invoke :c:member:`~PyTypeObject.tp_clear`.
1406
1407   More information about Python's garbage collection scheme can be found in
1408   section :ref:`supporting-cycle-detection`.
1409
1410   **Inheritance:**
1411
1412   Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear`
1413
1414   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_traverse` and the
1415   :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
1416   :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
1417   the subtype.
1418
1419
1420.. c:member:: richcmpfunc PyTypeObject.tp_richcompare
1421
1422   An optional pointer to the rich comparison function, whose signature is::
1423
1424      PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
1425
1426   The first parameter is guaranteed to be an instance of the type
1427   that is defined by :c:type:`PyTypeObject`.
1428
1429   The function should return the result of the comparison (usually ``Py_True``
1430   or ``Py_False``).  If the comparison is undefined, it must return
1431   ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and
1432   set an exception condition.
1433
1434   The following constants are defined to be used as the third argument for
1435   :c:member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:
1436
1437   +----------------+------------+
1438   | Constant       | Comparison |
1439   +================+============+
1440   | :const:`Py_LT` | ``<``      |
1441   +----------------+------------+
1442   | :const:`Py_LE` | ``<=``     |
1443   +----------------+------------+
1444   | :const:`Py_EQ` | ``==``     |
1445   +----------------+------------+
1446   | :const:`Py_NE` | ``!=``     |
1447   +----------------+------------+
1448   | :const:`Py_GT` | ``>``      |
1449   +----------------+------------+
1450   | :const:`Py_GE` | ``>=``     |
1451   +----------------+------------+
1452
1453   The following macro is defined to ease writing rich comparison functions:
1454
1455   .. c:macro:: Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
1456
1457      Return ``Py_True`` or ``Py_False`` from the function, depending on the
1458      result of a comparison.
1459      VAL_A and VAL_B must be orderable by C comparison operators (for example,
1460      they may be C ints or floats). The third argument specifies the requested
1461      operation, as for :c:func:`PyObject_RichCompare`.
1462
1463      The return value's reference count is properly incremented.
1464
1465      On error, sets an exception and returns ``NULL`` from the function.
1466
1467      .. versionadded:: 3.7
1468
1469   **Inheritance:**
1470
1471   Group: :attr:`tp_hash`, :attr:`tp_richcompare`
1472
1473   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_hash`:
1474   a subtype inherits :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` when
1475   the subtype's :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both
1476   ``NULL``.
1477
1478   **Default:**
1479
1480   :c:type:`PyBaseObject_Type` provides a :attr:`tp_richcompare`
1481   implementation, which may be inherited.  However, if only
1482   :attr:`tp_hash` is defined, not even the inherited function is used
1483   and instances of the type will not be able to participate in any
1484   comparisons.
1485
1486
1487.. c:member:: Py_ssize_t PyTypeObject.tp_weaklistoffset
1488
1489   If the instances of this type are weakly referenceable, this field is greater
1490   than zero and contains the offset in the instance structure of the weak
1491   reference list head (ignoring the GC header, if present); this offset is used by
1492   :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions.  The
1493   instance structure needs to include a field of type :c:type:`PyObject*` which is
1494   initialized to ``NULL``.
1495
1496   Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that is the list head for
1497   weak references to the type object itself.
1498
1499   **Inheritance:**
1500
1501   This field is inherited by subtypes, but see the rules listed below. A subtype
1502   may override this offset; this means that the subtype uses a different weak
1503   reference list head than the base type.  Since the list head is always found via
1504   :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem.
1505
1506   When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
1507   and none of its base types are weakly referenceable, the type is made weakly
1508   referenceable by adding a weak reference list head slot to the instance layout
1509   and setting the :c:member:`~PyTypeObject.tp_weaklistoffset` of that slot's offset.
1510
1511   When a type's :attr:`__slots__` declaration contains a slot named
1512   :attr:`__weakref__`, that slot becomes the weak reference list head for
1513   instances of the type, and the slot's offset is stored in the type's
1514   :c:member:`~PyTypeObject.tp_weaklistoffset`.
1515
1516   When a type's :attr:`__slots__` declaration does not contain a slot named
1517   :attr:`__weakref__`, the type inherits its :c:member:`~PyTypeObject.tp_weaklistoffset` from its
1518   base type.
1519
1520
1521.. c:member:: getiterfunc PyTypeObject.tp_iter
1522
1523   An optional pointer to a function that returns an :term:`iterator` for the
1524   object.  Its presence normally signals that the instances of this type are
1525   :term:`iterable` (although sequences may be iterable without this function).
1526
1527   This function has the same signature as :c:func:`PyObject_GetIter`::
1528
1529      PyObject *tp_iter(PyObject *self);
1530
1531   **Inheritance:**
1532
1533   This field is inherited by subtypes.
1534
1535
1536.. c:member:: iternextfunc PyTypeObject.tp_iternext
1537
1538   An optional pointer to a function that returns the next item in an
1539   :term:`iterator`. The signature is::
1540
1541      PyObject *tp_iternext(PyObject *self);
1542
1543   When the iterator is exhausted, it must return ``NULL``; a :exc:`StopIteration`
1544   exception may or may not be set.  When another error occurs, it must return
1545   ``NULL`` too.  Its presence signals that the instances of this type are
1546   iterators.
1547
1548   Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` function, and that
1549   function should return the iterator instance itself (not a new iterator
1550   instance).
1551
1552   This function has the same signature as :c:func:`PyIter_Next`.
1553
1554   **Inheritance:**
1555
1556   This field is inherited by subtypes.
1557
1558
1559.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods
1560
1561   An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMethodDef`
1562   structures, declaring regular methods of this type.
1563
1564   For each entry in the array, an entry is added to the type's dictionary (see
1565   :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor.
1566
1567   **Inheritance:**
1568
1569   This field is not inherited by subtypes (methods are inherited through a
1570   different mechanism).
1571
1572
1573.. c:member:: struct PyMemberDef* PyTypeObject.tp_members
1574
1575   An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMemberDef`
1576   structures, declaring regular data members (fields or slots) of instances of
1577   this type.
1578
1579   For each entry in the array, an entry is added to the type's dictionary (see
1580   :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor.
1581
1582   **Inheritance:**
1583
1584   This field is not inherited by subtypes (members are inherited through a
1585   different mechanism).
1586
1587
1588.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset
1589
1590   An optional pointer to a static ``NULL``-terminated array of :c:type:`PyGetSetDef`
1591   structures, declaring computed attributes of instances of this type.
1592
1593   For each entry in the array, an entry is added to the type's dictionary (see
1594   :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor.
1595
1596   **Inheritance:**
1597
1598   This field is not inherited by subtypes (computed attributes are inherited
1599   through a different mechanism).
1600
1601
1602.. c:member:: PyTypeObject* PyTypeObject.tp_base
1603
1604   An optional pointer to a base type from which type properties are inherited.  At
1605   this level, only single inheritance is supported; multiple inheritance require
1606   dynamically creating a type object by calling the metatype.
1607
1608   .. note::
1609
1610       .. from Modules/xxmodule.c
1611
1612       Slot initialization is subject to the rules of initializing globals.
1613       C99 requires the initializers to be "address constants".  Function
1614       designators like :c:func:`PyType_GenericNew`, with implicit conversion
1615       to a pointer, are valid C99 address constants.
1616
1617       However, the unary '&' operator applied to a non-static variable
1618       like :c:func:`PyBaseObject_Type` is not required to produce an address
1619       constant.  Compilers may support this (gcc does), MSVC does not.
1620       Both compilers are strictly standard conforming in this particular
1621       behavior.
1622
1623       Consequently, :c:member:`~PyTypeObject.tp_base` should be set in
1624       the extension module's init function.
1625
1626   **Inheritance:**
1627
1628   This field is not inherited by subtypes (obviously).
1629
1630   **Default:**
1631
1632   This field defaults to ``&PyBaseObject_Type`` (which to Python
1633   programmers is known as the type :class:`object`).
1634
1635
1636.. c:member:: PyObject* PyTypeObject.tp_dict
1637
1638   The type's dictionary is stored here by :c:func:`PyType_Ready`.
1639
1640   This field should normally be initialized to ``NULL`` before PyType_Ready is
1641   called; it may also be initialized to a dictionary containing initial attributes
1642   for the type.  Once :c:func:`PyType_Ready` has initialized the type, extra
1643   attributes for the type may be added to this dictionary only if they don't
1644   correspond to overloaded operations (like :meth:`__add__`).
1645
1646   **Inheritance:**
1647
1648   This field is not inherited by subtypes (though the attributes defined in here
1649   are inherited through a different mechanism).
1650
1651   **Default:**
1652
1653   If this field is ``NULL``, :c:func:`PyType_Ready` will assign a new
1654   dictionary to it.
1655
1656   .. warning::
1657
1658      It is not safe to use :c:func:`PyDict_SetItem` on or otherwise modify
1659      :c:member:`~PyTypeObject.tp_dict` with the dictionary C-API.
1660
1661
1662.. c:member:: descrgetfunc PyTypeObject.tp_descr_get
1663
1664   An optional pointer to a "descriptor get" function.
1665
1666   The function signature is::
1667
1668      PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
1669
1670   .. XXX explain more?
1671
1672   **Inheritance:**
1673
1674   This field is inherited by subtypes.
1675
1676
1677.. c:member:: descrsetfunc PyTypeObject.tp_descr_set
1678
1679   An optional pointer to a function for setting and deleting
1680   a descriptor's value.
1681
1682   The function signature is::
1683
1684      int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
1685
1686   The *value* argument is set to ``NULL`` to delete the value.
1687
1688   .. XXX explain more?
1689
1690   **Inheritance:**
1691
1692   This field is inherited by subtypes.
1693
1694
1695.. c:member:: Py_ssize_t PyTypeObject.tp_dictoffset
1696
1697   If the instances of this type have a dictionary containing instance variables,
1698   this field is non-zero and contains the offset in the instances of the type of
1699   the instance variable dictionary; this offset is used by
1700   :c:func:`PyObject_GenericGetAttr`.
1701
1702   Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is the dictionary for
1703   attributes of the type object itself.
1704
1705   If the value of this field is greater than zero, it specifies the offset from
1706   the start of the instance structure.  If the value is less than zero, it
1707   specifies the offset from the *end* of the instance structure.  A negative
1708   offset is more expensive to use, and should only be used when the instance
1709   structure contains a variable-length part.  This is used for example to add an
1710   instance variable dictionary to subtypes of :class:`str` or :class:`tuple`. Note
1711   that the :c:member:`~PyTypeObject.tp_basicsize` field should account for the dictionary added to
1712   the end in that case, even though the dictionary is not included in the basic
1713   object layout.  On a system with a pointer size of 4 bytes,
1714   :c:member:`~PyTypeObject.tp_dictoffset` should be set to ``-4`` to indicate that the dictionary is
1715   at the very end of the structure.
1716
1717   The real dictionary offset in an instance can be computed from a negative
1718   :c:member:`~PyTypeObject.tp_dictoffset` as follows::
1719
1720      dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
1721      if dictoffset is not aligned on sizeof(void*):
1722          round up to sizeof(void*)
1723
1724   where :c:member:`~PyTypeObject.tp_basicsize`, :c:member:`~PyTypeObject.tp_itemsize` and :c:member:`~PyTypeObject.tp_dictoffset` are
1725   taken from the type object, and :attr:`ob_size` is taken from the instance.  The
1726   absolute value is taken because ints use the sign of :attr:`ob_size` to
1727   store the sign of the number.  (There's never a need to do this calculation
1728   yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.)
1729
1730   **Inheritance:**
1731
1732   This field is inherited by subtypes, but see the rules listed below. A subtype
1733   may override this offset; this means that the subtype instances store the
1734   dictionary at a difference offset than the base type.  Since the dictionary is
1735   always found via :c:member:`~PyTypeObject.tp_dictoffset`, this should not be a problem.
1736
1737   When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
1738   and none of its base types has an instance variable dictionary, a dictionary
1739   slot is added to the instance layout and the :c:member:`~PyTypeObject.tp_dictoffset` is set to
1740   that slot's offset.
1741
1742   When a type defined by a class statement has a :attr:`__slots__` declaration,
1743   the type inherits its :c:member:`~PyTypeObject.tp_dictoffset` from its base type.
1744
1745   (Adding a slot named :attr:`~object.__dict__` to the :attr:`__slots__` declaration does
1746   not have the expected effect, it just causes confusion.  Maybe this should be
1747   added as a feature just like :attr:`__weakref__` though.)
1748
1749   **Default:**
1750
1751   This slot has no default.  For :ref:`static types <static-types>`, if the
1752   field is ``NULL`` then no :attr:`__dict__` gets created for instances.
1753
1754
1755.. c:member:: initproc PyTypeObject.tp_init
1756
1757   An optional pointer to an instance initialization function.
1758
1759   This function corresponds to the :meth:`__init__` method of classes.  Like
1760   :meth:`__init__`, it is possible to create an instance without calling
1761   :meth:`__init__`, and it is possible to reinitialize an instance by calling its
1762   :meth:`__init__` method again.
1763
1764   The function signature is::
1765
1766      int tp_init(PyObject *self, PyObject *args, PyObject *kwds);
1767
1768   The self argument is the instance to be initialized; the *args* and *kwds*
1769   arguments represent positional and keyword arguments of the call to
1770   :meth:`__init__`.
1771
1772   The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called when an instance is
1773   created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function
1774   has returned an instance of the type.  If the :c:member:`~PyTypeObject.tp_new` function returns an
1775   instance of some other type that is not a subtype of the original type, no
1776   :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a
1777   subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called.
1778
1779   Returns ``0`` on success, ``-1`` and sets an exception on error.
1780
1781   **Inheritance:**
1782
1783   This field is inherited by subtypes.
1784
1785   **Default:**
1786
1787   For :ref:`static types <static-types>` this field does not have a default.
1788
1789
1790.. c:member:: allocfunc PyTypeObject.tp_alloc
1791
1792   An optional pointer to an instance allocation function.
1793
1794   The function signature is::
1795
1796      PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
1797
1798   **Inheritance:**
1799
1800   This field is inherited by static subtypes, but not by dynamic
1801   subtypes (subtypes created by a class statement).
1802
1803   **Default:**
1804
1805   For dynamic subtypes, this field is always set to
1806   :c:func:`PyType_GenericAlloc`, to force a standard heap
1807   allocation strategy.
1808
1809   For static subtypes, :c:type:`PyBaseObject_Type` uses
1810   :c:func:`PyType_GenericAlloc`.  That is the recommended value
1811   for all statically defined types.
1812
1813
1814.. c:member:: newfunc PyTypeObject.tp_new
1815
1816   An optional pointer to an instance creation function.
1817
1818   The function signature is::
1819
1820      PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
1821
1822   The *subtype* argument is the type of the object being created; the *args* and
1823   *kwds* arguments represent positional and keyword arguments of the call to the
1824   type.  Note that *subtype* doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new`
1825   function is called; it may be a subtype of that type (but not an unrelated
1826   type).
1827
1828   The :c:member:`~PyTypeObject.tp_new` function should call ``subtype->tp_alloc(subtype, nitems)``
1829   to allocate space for the object, and then do only as much further
1830   initialization as is absolutely necessary.  Initialization that can safely be
1831   ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler.  A good
1832   rule of thumb is that for immutable types, all initialization should take place
1833   in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be
1834   deferred to :c:member:`~PyTypeObject.tp_init`.
1835
1836   Set the :const:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag to disallow creating
1837   instances of the type in Python.
1838
1839   **Inheritance:**
1840
1841   This field is inherited by subtypes, except it is not inherited by
1842   :ref:`static types <static-types>` whose :c:member:`~PyTypeObject.tp_base`
1843   is ``NULL`` or ``&PyBaseObject_Type``.
1844
1845   **Default:**
1846
1847   For :ref:`static types <static-types>` this field has no default.
1848   This means if the slot is defined as ``NULL``, the type cannot be called
1849   to create new instances; presumably there is some other way to create
1850   instances, like a factory function.
1851
1852
1853.. c:member:: freefunc PyTypeObject.tp_free
1854
1855   An optional pointer to an instance deallocation function.  Its signature is::
1856
1857      void tp_free(void *self);
1858
1859   An initializer that is compatible with this signature is :c:func:`PyObject_Free`.
1860
1861   **Inheritance:**
1862
1863   This field is inherited by static subtypes, but not by dynamic
1864   subtypes (subtypes created by a class statement)
1865
1866   **Default:**
1867
1868   In dynamic subtypes, this field is set to a deallocator suitable to
1869   match :c:func:`PyType_GenericAlloc` and the value of the
1870   :const:`Py_TPFLAGS_HAVE_GC` flag bit.
1871
1872   For static subtypes, :c:type:`PyBaseObject_Type` uses PyObject_Del.
1873
1874
1875.. c:member:: inquiry PyTypeObject.tp_is_gc
1876
1877   An optional pointer to a function called by the garbage collector.
1878
1879   The garbage collector needs to know whether a particular object is collectible
1880   or not.  Normally, it is sufficient to look at the object's type's
1881   :c:member:`~PyTypeObject.tp_flags` field, and check the :const:`Py_TPFLAGS_HAVE_GC` flag bit.  But
1882   some types have a mixture of statically and dynamically allocated instances, and
1883   the statically allocated instances are not collectible.  Such types should
1884   define this function; it should return ``1`` for a collectible instance, and
1885   ``0`` for a non-collectible instance. The signature is::
1886
1887      int tp_is_gc(PyObject *self);
1888
1889   (The only example of this are types themselves.  The metatype,
1890   :c:data:`PyType_Type`, defines this function to distinguish between statically
1891   and :ref:`dynamically allocated types <heap-types>`.)
1892
1893   **Inheritance:**
1894
1895   This field is inherited by subtypes.
1896
1897   **Default:**
1898
1899   This slot has no default.  If this field is ``NULL``,
1900   :const:`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent.
1901
1902
1903.. c:member:: PyObject* PyTypeObject.tp_bases
1904
1905   Tuple of base types.
1906
1907   This is set for types created by a class statement.  It should be ``NULL`` for
1908   statically defined types.
1909
1910   **Inheritance:**
1911
1912   This field is not inherited.
1913
1914
1915.. c:member:: PyObject* PyTypeObject.tp_mro
1916
1917   Tuple containing the expanded set of base types, starting with the type itself
1918   and ending with :class:`object`, in Method Resolution Order.
1919
1920
1921   **Inheritance:**
1922
1923   This field is not inherited; it is calculated fresh by
1924   :c:func:`PyType_Ready`.
1925
1926
1927.. c:member:: PyObject* PyTypeObject.tp_cache
1928
1929   Unused.  Internal use only.
1930
1931   **Inheritance:**
1932
1933   This field is not inherited.
1934
1935
1936.. c:member:: PyObject* PyTypeObject.tp_subclasses
1937
1938   List of weak references to subclasses.  Internal use only.
1939
1940   **Inheritance:**
1941
1942   This field is not inherited.
1943
1944
1945.. c:member:: PyObject* PyTypeObject.tp_weaklist
1946
1947   Weak reference list head, for weak references to this type object.  Not
1948   inherited.  Internal use only.
1949
1950   **Inheritance:**
1951
1952   This field is not inherited.
1953
1954
1955.. c:member:: destructor PyTypeObject.tp_del
1956
1957   This field is deprecated.  Use :c:member:`~PyTypeObject.tp_finalize` instead.
1958
1959
1960.. c:member:: unsigned int PyTypeObject.tp_version_tag
1961
1962   Used to index into the method cache.  Internal use only.
1963
1964   **Inheritance:**
1965
1966   This field is not inherited.
1967
1968
1969.. c:member:: destructor PyTypeObject.tp_finalize
1970
1971   An optional pointer to an instance finalization function.  Its signature is::
1972
1973      void tp_finalize(PyObject *self);
1974
1975   If :c:member:`~PyTypeObject.tp_finalize` is set, the interpreter calls it once when
1976   finalizing an instance.  It is called either from the garbage
1977   collector (if the instance is part of an isolated reference cycle) or
1978   just before the object is deallocated.  Either way, it is guaranteed
1979   to be called before attempting to break reference cycles, ensuring
1980   that it finds the object in a sane state.
1981
1982   :c:member:`~PyTypeObject.tp_finalize` should not mutate the current exception status;
1983   therefore, a recommended way to write a non-trivial finalizer is::
1984
1985      static void
1986      local_finalize(PyObject *self)
1987      {
1988          PyObject *error_type, *error_value, *error_traceback;
1989
1990          /* Save the current exception, if any. */
1991          PyErr_Fetch(&error_type, &error_value, &error_traceback);
1992
1993          /* ... */
1994
1995          /* Restore the saved exception. */
1996          PyErr_Restore(error_type, error_value, error_traceback);
1997      }
1998
1999   For this field to be taken into account (even through inheritance),
2000   you must also set the :const:`Py_TPFLAGS_HAVE_FINALIZE` flags bit.
2001
2002   **Inheritance:**
2003
2004   This field is inherited by subtypes.
2005
2006   .. versionadded:: 3.4
2007
2008   .. seealso:: "Safe object finalization" (:pep:`442`)
2009
2010
2011.. c:member:: vectorcallfunc PyTypeObject.tp_vectorcall
2012
2013   Vectorcall function to use for calls of this type object.
2014   In other words, it is used to implement
2015   :ref:`vectorcall <vectorcall>` for ``type.__call__``.
2016   If ``tp_vectorcall`` is ``NULL``, the default call implementation
2017   using :attr:`__new__` and :attr:`__init__` is used.
2018
2019   **Inheritance:**
2020
2021   This field is never inherited.
2022
2023   .. versionadded:: 3.9 (the field exists since 3.8 but it's only used since 3.9)
2024
2025
2026Also, note that, in a garbage collected Python, :c:member:`~PyTypeObject.tp_dealloc` may be called from
2027any Python thread, not just the thread which created the object (if the object
2028becomes part of a refcount cycle, that cycle might be collected by a garbage
2029collection on any thread).  This is not a problem for Python API calls, since
2030the thread on which tp_dealloc is called will own the Global Interpreter Lock
2031(GIL). However, if the object being destroyed in turn destroys objects from some
2032other C or C++ library, care should be taken to ensure that destroying those
2033objects on the thread which called tp_dealloc will not violate any assumptions
2034of the library.
2035
2036
2037.. _static-types:
2038
2039Static Types
2040------------
2041
2042Traditionally, types defined in C code are *static*, that is,
2043a static :c:type:`PyTypeObject` structure is defined directly in code
2044and initialized using :c:func:`PyType_Ready`.
2045
2046This results in types that are limited relative to types defined in Python:
2047
2048* Static types are limited to one base, i.e. they cannot use multiple
2049  inheritance.
2050* Static type objects (but not necessarily their instances) are immutable.
2051  It is not possible to add or modify the type object's attributes from Python.
2052* Static type objects are shared across
2053  :ref:`sub-interpreters <sub-interpreter-support>`, so they should not
2054  include any subinterpreter-specific state.
2055
2056Also, since :c:type:`PyTypeObject` is not part of the :ref:`stable ABI <stable>`,
2057any extension modules using static types must be compiled for a specific
2058Python minor version.
2059
2060
2061.. _heap-types:
2062
2063Heap Types
2064----------
2065
2066An alternative to :ref:`static types <static-types>` is *heap-allocated types*,
2067or *heap types* for short, which correspond closely to classes created by
2068Python's ``class`` statement. Heap types have the :const:`Py_TPFLAGS_HEAPTYPE`
2069flag set.
2070
2071This is done by filling a :c:type:`PyType_Spec` structure and calling
2072:c:func:`PyType_FromSpec`, :c:func:`PyType_FromSpecWithBases`,
2073or :c:func:`PyType_FromModuleAndSpec`.
2074
2075
2076.. _number-structs:
2077
2078Number Object Structures
2079========================
2080
2081.. sectionauthor:: Amaury Forgeot d'Arc
2082
2083
2084.. c:type:: PyNumberMethods
2085
2086   This structure holds pointers to the functions which an object uses to
2087   implement the number protocol.  Each function is used by the function of
2088   similar name documented in the :ref:`number` section.
2089
2090   .. XXX Drop the definition?
2091
2092   Here is the structure definition::
2093
2094       typedef struct {
2095            binaryfunc nb_add;
2096            binaryfunc nb_subtract;
2097            binaryfunc nb_multiply;
2098            binaryfunc nb_remainder;
2099            binaryfunc nb_divmod;
2100            ternaryfunc nb_power;
2101            unaryfunc nb_negative;
2102            unaryfunc nb_positive;
2103            unaryfunc nb_absolute;
2104            inquiry nb_bool;
2105            unaryfunc nb_invert;
2106            binaryfunc nb_lshift;
2107            binaryfunc nb_rshift;
2108            binaryfunc nb_and;
2109            binaryfunc nb_xor;
2110            binaryfunc nb_or;
2111            unaryfunc nb_int;
2112            void *nb_reserved;
2113            unaryfunc nb_float;
2114
2115            binaryfunc nb_inplace_add;
2116            binaryfunc nb_inplace_subtract;
2117            binaryfunc nb_inplace_multiply;
2118            binaryfunc nb_inplace_remainder;
2119            ternaryfunc nb_inplace_power;
2120            binaryfunc nb_inplace_lshift;
2121            binaryfunc nb_inplace_rshift;
2122            binaryfunc nb_inplace_and;
2123            binaryfunc nb_inplace_xor;
2124            binaryfunc nb_inplace_or;
2125
2126            binaryfunc nb_floor_divide;
2127            binaryfunc nb_true_divide;
2128            binaryfunc nb_inplace_floor_divide;
2129            binaryfunc nb_inplace_true_divide;
2130
2131            unaryfunc nb_index;
2132
2133            binaryfunc nb_matrix_multiply;
2134            binaryfunc nb_inplace_matrix_multiply;
2135       } PyNumberMethods;
2136
2137   .. note::
2138
2139      Binary and ternary functions must check the type of all their operands,
2140      and implement the necessary conversions (at least one of the operands is
2141      an instance of the defined type).  If the operation is not defined for the
2142      given operands, binary and ternary functions must return
2143      ``Py_NotImplemented``, if another error occurred they must return ``NULL``
2144      and set an exception.
2145
2146   .. note::
2147
2148      The :c:data:`nb_reserved` field should always be ``NULL``.  It
2149      was previously called :c:data:`nb_long`, and was renamed in
2150      Python 3.0.1.
2151
2152.. c:member:: binaryfunc PyNumberMethods.nb_add
2153.. c:member:: binaryfunc PyNumberMethods.nb_subtract
2154.. c:member:: binaryfunc PyNumberMethods.nb_multiply
2155.. c:member:: binaryfunc PyNumberMethods.nb_remainder
2156.. c:member:: binaryfunc PyNumberMethods.nb_divmod
2157.. c:member:: ternaryfunc PyNumberMethods.nb_power
2158.. c:member:: unaryfunc PyNumberMethods.nb_negative
2159.. c:member:: unaryfunc PyNumberMethods.nb_positive
2160.. c:member:: unaryfunc PyNumberMethods.nb_absolute
2161.. c:member:: inquiry PyNumberMethods.nb_bool
2162.. c:member:: unaryfunc PyNumberMethods.nb_invert
2163.. c:member:: binaryfunc PyNumberMethods.nb_lshift
2164.. c:member:: binaryfunc PyNumberMethods.nb_rshift
2165.. c:member:: binaryfunc PyNumberMethods.nb_and
2166.. c:member:: binaryfunc PyNumberMethods.nb_xor
2167.. c:member:: binaryfunc PyNumberMethods.nb_or
2168.. c:member:: unaryfunc PyNumberMethods.nb_int
2169.. c:member:: void *PyNumberMethods.nb_reserved
2170.. c:member:: unaryfunc PyNumberMethods.nb_float
2171.. c:member:: binaryfunc PyNumberMethods.nb_inplace_add
2172.. c:member:: binaryfunc PyNumberMethods.nb_inplace_subtract
2173.. c:member:: binaryfunc PyNumberMethods.nb_inplace_multiply
2174.. c:member:: binaryfunc PyNumberMethods.nb_inplace_remainder
2175.. c:member:: ternaryfunc PyNumberMethods.nb_inplace_power
2176.. c:member:: binaryfunc PyNumberMethods.nb_inplace_lshift
2177.. c:member:: binaryfunc PyNumberMethods.nb_inplace_rshift
2178.. c:member:: binaryfunc PyNumberMethods.nb_inplace_and
2179.. c:member:: binaryfunc PyNumberMethods.nb_inplace_xor
2180.. c:member:: binaryfunc PyNumberMethods.nb_inplace_or
2181.. c:member:: binaryfunc PyNumberMethods.nb_floor_divide
2182.. c:member:: binaryfunc PyNumberMethods.nb_true_divide
2183.. c:member:: binaryfunc PyNumberMethods.nb_inplace_floor_divide
2184.. c:member:: binaryfunc PyNumberMethods.nb_inplace_true_divide
2185.. c:member:: unaryfunc PyNumberMethods.nb_index
2186.. c:member:: binaryfunc PyNumberMethods.nb_matrix_multiply
2187.. c:member:: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
2188
2189
2190.. _mapping-structs:
2191
2192Mapping Object Structures
2193=========================
2194
2195.. sectionauthor:: Amaury Forgeot d'Arc
2196
2197
2198.. c:type:: PyMappingMethods
2199
2200   This structure holds pointers to the functions which an object uses to
2201   implement the mapping protocol.  It has three members:
2202
2203.. c:member:: lenfunc PyMappingMethods.mp_length
2204
2205   This function is used by :c:func:`PyMapping_Size` and
2206   :c:func:`PyObject_Size`, and has the same signature.  This slot may be set to
2207   ``NULL`` if the object has no defined length.
2208
2209.. c:member:: binaryfunc PyMappingMethods.mp_subscript
2210
2211   This function is used by :c:func:`PyObject_GetItem` and
2212   :c:func:`PySequence_GetSlice`, and has the same signature as
2213   :c:func:`!PyObject_GetItem`.  This slot must be filled for the
2214   :c:func:`PyMapping_Check` function to return ``1``, it can be ``NULL``
2215   otherwise.
2216
2217.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript
2218
2219   This function is used by :c:func:`PyObject_SetItem`,
2220   :c:func:`PyObject_DelItem`, :c:func:`PyObject_SetSlice` and
2221   :c:func:`PyObject_DelSlice`.  It has the same signature as
2222   :c:func:`!PyObject_SetItem`, but *v* can also be set to ``NULL`` to delete
2223   an item.  If this slot is ``NULL``, the object does not support item
2224   assignment and deletion.
2225
2226
2227.. _sequence-structs:
2228
2229Sequence Object Structures
2230==========================
2231
2232.. sectionauthor:: Amaury Forgeot d'Arc
2233
2234
2235.. c:type:: PySequenceMethods
2236
2237   This structure holds pointers to the functions which an object uses to
2238   implement the sequence protocol.
2239
2240.. c:member:: lenfunc PySequenceMethods.sq_length
2241
2242   This function is used by :c:func:`PySequence_Size` and
2243   :c:func:`PyObject_Size`, and has the same signature.  It is also used for
2244   handling negative indices via the :c:member:`~PySequenceMethods.sq_item`
2245   and the :c:member:`~PySequenceMethods.sq_ass_item` slots.
2246
2247.. c:member:: binaryfunc PySequenceMethods.sq_concat
2248
2249   This function is used by :c:func:`PySequence_Concat` and has the same
2250   signature.  It is also used by the ``+`` operator, after trying the numeric
2251   addition via the :c:member:`~PyNumberMethods.nb_add` slot.
2252
2253.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat
2254
2255   This function is used by :c:func:`PySequence_Repeat` and has the same
2256   signature.  It is also used by the ``*`` operator, after trying numeric
2257   multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot.
2258
2259.. c:member:: ssizeargfunc PySequenceMethods.sq_item
2260
2261   This function is used by :c:func:`PySequence_GetItem` and has the same
2262   signature.  It is also used by :c:func:`PyObject_GetItem`, after trying
2263   the subscription via the :c:member:`~PyMappingMethods.mp_subscript` slot.
2264   This slot must be filled for the :c:func:`PySequence_Check`
2265   function to return ``1``, it can be ``NULL`` otherwise.
2266
2267   Negative indexes are handled as follows: if the :attr:`sq_length` slot is
2268   filled, it is called and the sequence length is used to compute a positive
2269   index which is passed to :attr:`sq_item`.  If :attr:`sq_length` is ``NULL``,
2270   the index is passed as is to the function.
2271
2272.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item
2273
2274   This function is used by :c:func:`PySequence_SetItem` and has the same
2275   signature.  It is also used by :c:func:`PyObject_SetItem` and
2276   :c:func:`PyObject_DelItem`, after trying the item assignment and deletion
2277   via the :c:member:`~PyMappingMethods.mp_ass_subscript` slot.
2278   This slot may be left to ``NULL`` if the object does not support
2279   item assignment and deletion.
2280
2281.. c:member:: objobjproc PySequenceMethods.sq_contains
2282
2283   This function may be used by :c:func:`PySequence_Contains` and has the same
2284   signature.  This slot may be left to ``NULL``, in this case
2285   :c:func:`!PySequence_Contains` simply traverses the sequence until it
2286   finds a match.
2287
2288.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat
2289
2290   This function is used by :c:func:`PySequence_InPlaceConcat` and has the same
2291   signature.  It should modify its first operand, and return it.  This slot
2292   may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceConcat`
2293   will fall back to :c:func:`PySequence_Concat`.  It is also used by the
2294   augmented assignment ``+=``, after trying numeric in-place addition
2295   via the :c:member:`~PyNumberMethods.nb_inplace_add` slot.
2296
2297.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat
2298
2299   This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same
2300   signature.  It should modify its first operand, and return it.  This slot
2301   may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceRepeat`
2302   will fall back to :c:func:`PySequence_Repeat`.  It is also used by the
2303   augmented assignment ``*=``, after trying numeric in-place multiplication
2304   via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot.
2305
2306
2307.. _buffer-structs:
2308
2309Buffer Object Structures
2310========================
2311
2312.. sectionauthor:: Greg J. Stein <greg@lyra.org>
2313.. sectionauthor:: Benjamin Peterson
2314.. sectionauthor:: Stefan Krah
2315
2316.. c:type:: PyBufferProcs
2317
2318   This structure holds pointers to the functions required by the
2319   :ref:`Buffer protocol <bufferobjects>`. The protocol defines how
2320   an exporter object can expose its internal data to consumer objects.
2321
2322.. c:member:: getbufferproc PyBufferProcs.bf_getbuffer
2323
2324   The signature of this function is::
2325
2326       int (PyObject *exporter, Py_buffer *view, int flags);
2327
2328   Handle a request to *exporter* to fill in *view* as specified by *flags*.
2329   Except for point (3), an implementation of this function MUST take these
2330   steps:
2331
2332   (1) Check if the request can be met. If not, raise :c:data:`PyExc_BufferError`,
2333       set :c:data:`view->obj` to ``NULL`` and return ``-1``.
2334
2335   (2) Fill in the requested fields.
2336
2337   (3) Increment an internal counter for the number of exports.
2338
2339   (4) Set :c:data:`view->obj` to *exporter* and increment :c:data:`view->obj`.
2340
2341   (5) Return ``0``.
2342
2343   If *exporter* is part of a chain or tree of buffer providers, two main
2344   schemes can be used:
2345
2346   * Re-export: Each member of the tree acts as the exporting object and
2347     sets :c:data:`view->obj` to a new reference to itself.
2348
2349   * Redirect: The buffer request is redirected to the root object of the
2350     tree. Here, :c:data:`view->obj` will be a new reference to the root
2351     object.
2352
2353   The individual fields of *view* are described in section
2354   :ref:`Buffer structure <buffer-structure>`, the rules how an exporter
2355   must react to specific requests are in section
2356   :ref:`Buffer request types <buffer-request-types>`.
2357
2358   All memory pointed to in the :c:type:`Py_buffer` structure belongs to
2359   the exporter and must remain valid until there are no consumers left.
2360   :c:member:`~Py_buffer.format`, :c:member:`~Py_buffer.shape`,
2361   :c:member:`~Py_buffer.strides`, :c:member:`~Py_buffer.suboffsets`
2362   and :c:member:`~Py_buffer.internal`
2363   are read-only for the consumer.
2364
2365   :c:func:`PyBuffer_FillInfo` provides an easy way of exposing a simple
2366   bytes buffer while dealing correctly with all request types.
2367
2368   :c:func:`PyObject_GetBuffer` is the interface for the consumer that
2369   wraps this function.
2370
2371.. c:member:: releasebufferproc PyBufferProcs.bf_releasebuffer
2372
2373   The signature of this function is::
2374
2375       void (PyObject *exporter, Py_buffer *view);
2376
2377   Handle a request to release the resources of the buffer. If no resources
2378   need to be released, :c:member:`PyBufferProcs.bf_releasebuffer` may be
2379   ``NULL``. Otherwise, a standard implementation of this function will take
2380   these optional steps:
2381
2382   (1) Decrement an internal counter for the number of exports.
2383
2384   (2) If the counter is ``0``, free all memory associated with *view*.
2385
2386   The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep
2387   track of buffer-specific resources. This field is guaranteed to remain
2388   constant, while a consumer MAY pass a copy of the original buffer as the
2389   *view* argument.
2390
2391
2392   This function MUST NOT decrement :c:data:`view->obj`, since that is
2393   done automatically in :c:func:`PyBuffer_Release` (this scheme is
2394   useful for breaking reference cycles).
2395
2396
2397   :c:func:`PyBuffer_Release` is the interface for the consumer that
2398   wraps this function.
2399
2400
2401.. _async-structs:
2402
2403
2404Async Object Structures
2405=======================
2406
2407.. sectionauthor:: Yury Selivanov <yselivanov@sprymix.com>
2408
2409.. versionadded:: 3.5
2410
2411.. c:type:: PyAsyncMethods
2412
2413   This structure holds pointers to the functions required to implement
2414   :term:`awaitable` and :term:`asynchronous iterator` objects.
2415
2416   Here is the structure definition::
2417
2418        typedef struct {
2419            unaryfunc am_await;
2420            unaryfunc am_aiter;
2421            unaryfunc am_anext;
2422            sendfunc am_send;
2423        } PyAsyncMethods;
2424
2425.. c:member:: unaryfunc PyAsyncMethods.am_await
2426
2427   The signature of this function is::
2428
2429      PyObject *am_await(PyObject *self);
2430
2431   The returned object must be an :term:`iterator`, i.e. :c:func:`PyIter_Check`
2432   must return ``1`` for it.
2433
2434   This slot may be set to ``NULL`` if an object is not an :term:`awaitable`.
2435
2436.. c:member:: unaryfunc PyAsyncMethods.am_aiter
2437
2438   The signature of this function is::
2439
2440      PyObject *am_aiter(PyObject *self);
2441
2442   Must return an :term:`awaitable` object.  See :meth:`__anext__` for details.
2443
2444   This slot may be set to ``NULL`` if an object does not implement
2445   asynchronous iteration protocol.
2446
2447.. c:member:: unaryfunc PyAsyncMethods.am_anext
2448
2449   The signature of this function is::
2450
2451      PyObject *am_anext(PyObject *self);
2452
2453   Must return an :term:`awaitable` object.  See :meth:`__anext__` for details.
2454   This slot may be set to ``NULL``.
2455
2456.. c:member:: sendfunc PyAsyncMethods.am_send
2457
2458   The signature of this function is::
2459
2460      PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
2461
2462   See :c:func:`PyIter_Send` for details.
2463   This slot may be set to ``NULL``.
2464
2465   .. versionadded:: 3.10
2466
2467
2468.. _slot-typedefs:
2469
2470Slot Type typedefs
2471==================
2472
2473.. c:type:: PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
2474
2475   The purpose of this function is to separate memory allocation from memory
2476   initialization.  It should return a pointer to a block of memory of adequate
2477   length for the instance, suitably aligned, and initialized to zeros, but with
2478   :attr:`ob_refcnt` set to ``1`` and :attr:`ob_type` set to the type argument.  If
2479   the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :attr:`ob_size` field
2480   should be initialized to *nitems* and the length of the allocated memory block
2481   should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of
2482   ``sizeof(void*)``; otherwise, *nitems* is not used and the length of the block
2483   should be :c:member:`~PyTypeObject.tp_basicsize`.
2484
2485   This function should not do any other instance initialization, not even to
2486   allocate additional memory; that should be done by :c:member:`~PyTypeObject.tp_new`.
2487
2488.. c:type:: void (*destructor)(PyObject *)
2489
2490.. c:type:: void (*freefunc)(void *)
2491
2492   See :c:member:`~PyTypeObject.tp_free`.
2493
2494.. c:type:: PyObject *(*newfunc)(PyObject *, PyObject *, PyObject *)
2495
2496   See :c:member:`~PyTypeObject.tp_new`.
2497
2498.. c:type:: int (*initproc)(PyObject *, PyObject *, PyObject *)
2499
2500   See :c:member:`~PyTypeObject.tp_init`.
2501
2502.. c:type:: PyObject *(*reprfunc)(PyObject *)
2503
2504   See :c:member:`~PyTypeObject.tp_repr`.
2505
2506.. c:type:: PyObject *(*getattrfunc)(PyObject *self, char *attr)
2507
2508   Return the value of the named attribute for the object.
2509
2510.. c:type:: int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
2511
2512   Set the value of the named attribute for the object.
2513   The value argument is set to ``NULL`` to delete the attribute.
2514
2515.. c:type:: PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
2516
2517   Return the value of the named attribute for the object.
2518
2519   See :c:member:`~PyTypeObject.tp_getattro`.
2520
2521.. c:type:: int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
2522
2523   Set the value of the named attribute for the object.
2524   The value argument is set to ``NULL`` to delete the attribute.
2525
2526   See :c:member:`~PyTypeObject.tp_setattro`.
2527
2528.. c:type:: PyObject *(*descrgetfunc)(PyObject *, PyObject *, PyObject *)
2529
2530   See :c:member:`~PyTypeObject.tp_descrget`.
2531
2532.. c:type:: int (*descrsetfunc)(PyObject *, PyObject *, PyObject *)
2533
2534   See :c:member:`~PyTypeObject.tp_descrset`.
2535
2536.. c:type:: Py_hash_t (*hashfunc)(PyObject *)
2537
2538   See :c:member:`~PyTypeObject.tp_hash`.
2539
2540.. c:type:: PyObject *(*richcmpfunc)(PyObject *, PyObject *, int)
2541
2542   See :c:member:`~PyTypeObject.tp_richcompare`.
2543
2544.. c:type:: PyObject *(*getiterfunc)(PyObject *)
2545
2546   See :c:member:`~PyTypeObject.tp_iter`.
2547
2548.. c:type:: PyObject *(*iternextfunc)(PyObject *)
2549
2550   See :c:member:`~PyTypeObject.tp_iternext`.
2551
2552.. c:type:: Py_ssize_t (*lenfunc)(PyObject *)
2553
2554.. c:type:: int (*getbufferproc)(PyObject *, Py_buffer *, int)
2555
2556.. c:type:: void (*releasebufferproc)(PyObject *, Py_buffer *)
2557
2558.. c:type:: PyObject *(*unaryfunc)(PyObject *)
2559
2560.. c:type:: PyObject *(*binaryfunc)(PyObject *, PyObject *)
2561
2562.. c:type:: PySendResult (*sendfunc)(PyObject *, PyObject *, PyObject **)
2563
2564   See :c:member:`~PyAsyncMethods.am_send`.
2565
2566.. c:type:: PyObject *(*ternaryfunc)(PyObject *, PyObject *, PyObject *)
2567
2568.. c:type:: PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t)
2569
2570.. c:type:: int (*ssizeobjargproc)(PyObject *, Py_ssize_t)
2571
2572.. c:type:: int (*objobjproc)(PyObject *, PyObject *)
2573
2574.. c:type:: int (*objobjargproc)(PyObject *, PyObject *, PyObject *)
2575
2576
2577.. _typedef-examples:
2578
2579Examples
2580========
2581
2582The following are simple examples of Python type definitions.  They
2583include common usage you may encounter.  Some demonstrate tricky corner
2584cases.  For more examples, practical info, and a tutorial, see
2585:ref:`defining-new-types` and :ref:`new-types-topics`.
2586
2587A basic :ref:`static type <static-types>`::
2588
2589   typedef struct {
2590       PyObject_HEAD
2591       const char *data;
2592   } MyObject;
2593
2594   static PyTypeObject MyObject_Type = {
2595       PyVarObject_HEAD_INIT(NULL, 0)
2596       .tp_name = "mymod.MyObject",
2597       .tp_basicsize = sizeof(MyObject),
2598       .tp_doc = "My objects",
2599       .tp_new = myobj_new,
2600       .tp_dealloc = (destructor)myobj_dealloc,
2601       .tp_repr = (reprfunc)myobj_repr,
2602   };
2603
2604You may also find older code (especially in the CPython code base)
2605with a more verbose initializer::
2606
2607   static PyTypeObject MyObject_Type = {
2608       PyVarObject_HEAD_INIT(NULL, 0)
2609       "mymod.MyObject",               /* tp_name */
2610       sizeof(MyObject),               /* tp_basicsize */
2611       0,                              /* tp_itemsize */
2612       (destructor)myobj_dealloc,      /* tp_dealloc */
2613       0,                              /* tp_vectorcall_offset */
2614       0,                              /* tp_getattr */
2615       0,                              /* tp_setattr */
2616       0,                              /* tp_as_async */
2617       (reprfunc)myobj_repr,           /* tp_repr */
2618       0,                              /* tp_as_number */
2619       0,                              /* tp_as_sequence */
2620       0,                              /* tp_as_mapping */
2621       0,                              /* tp_hash */
2622       0,                              /* tp_call */
2623       0,                              /* tp_str */
2624       0,                              /* tp_getattro */
2625       0,                              /* tp_setattro */
2626       0,                              /* tp_as_buffer */
2627       0,                              /* tp_flags */
2628       "My objects",                   /* tp_doc */
2629       0,                              /* tp_traverse */
2630       0,                              /* tp_clear */
2631       0,                              /* tp_richcompare */
2632       0,                              /* tp_weaklistoffset */
2633       0,                              /* tp_iter */
2634       0,                              /* tp_iternext */
2635       0,                              /* tp_methods */
2636       0,                              /* tp_members */
2637       0,                              /* tp_getset */
2638       0,                              /* tp_base */
2639       0,                              /* tp_dict */
2640       0,                              /* tp_descr_get */
2641       0,                              /* tp_descr_set */
2642       0,                              /* tp_dictoffset */
2643       0,                              /* tp_init */
2644       0,                              /* tp_alloc */
2645       myobj_new,                      /* tp_new */
2646   };
2647
2648A type that supports weakrefs, instance dicts, and hashing::
2649
2650   typedef struct {
2651       PyObject_HEAD
2652       const char *data;
2653       PyObject *inst_dict;
2654       PyObject *weakreflist;
2655   } MyObject;
2656
2657   static PyTypeObject MyObject_Type = {
2658       PyVarObject_HEAD_INIT(NULL, 0)
2659       .tp_name = "mymod.MyObject",
2660       .tp_basicsize = sizeof(MyObject),
2661       .tp_doc = "My objects",
2662       .tp_weaklistoffset = offsetof(MyObject, weakreflist),
2663       .tp_dictoffset = offsetof(MyObject, inst_dict),
2664       .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2665       .tp_new = myobj_new,
2666       .tp_traverse = (traverseproc)myobj_traverse,
2667       .tp_clear = (inquiry)myobj_clear,
2668       .tp_alloc = PyType_GenericNew,
2669       .tp_dealloc = (destructor)myobj_dealloc,
2670       .tp_repr = (reprfunc)myobj_repr,
2671       .tp_hash = (hashfunc)myobj_hash,
2672       .tp_richcompare = PyBaseObject_Type.tp_richcompare,
2673   };
2674
2675A str subclass that cannot be subclassed and cannot be called
2676to create instances (e.g. uses a separate factory func) using
2677:c:data:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag::
2678
2679   typedef struct {
2680       PyUnicodeObject raw;
2681       char *extra;
2682   } MyStr;
2683
2684   static PyTypeObject MyStr_Type = {
2685       PyVarObject_HEAD_INIT(NULL, 0)
2686       .tp_name = "mymod.MyStr",
2687       .tp_basicsize = sizeof(MyStr),
2688       .tp_base = NULL,  // set to &PyUnicode_Type in module init
2689       .tp_doc = "my custom str",
2690       .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
2691       .tp_repr = (reprfunc)myobj_repr,
2692   };
2693
2694The simplest :ref:`static type <static-types>` with fixed-length instances::
2695
2696   typedef struct {
2697       PyObject_HEAD
2698   } MyObject;
2699
2700   static PyTypeObject MyObject_Type = {
2701       PyVarObject_HEAD_INIT(NULL, 0)
2702       .tp_name = "mymod.MyObject",
2703   };
2704
2705The simplest :ref:`static type <static-types>` with variable-length instances::
2706
2707   typedef struct {
2708       PyObject_VAR_HEAD
2709       const char *data[1];
2710   } MyObject;
2711
2712   static PyTypeObject MyObject_Type = {
2713       PyVarObject_HEAD_INIT(NULL, 0)
2714       .tp_name = "mymod.MyObject",
2715       .tp_basicsize = sizeof(MyObject) - sizeof(char *),
2716       .tp_itemsize = sizeof(char *),
2717   };
2718