Debian Codegraph @

Doc/c-api/typeobj.rst

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