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