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:`PyObject.ob_refcnt`
496
497 The type object's reference count is 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:`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:`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()` macro.
542
543 **Inheritance:**
544
545 This field is not inherited by subtypes.
546
547
548 PyTypeObject Slots
549 ------------------
550
551 Each slot has a section describing inheritance. If :c:func:`PyType_Ready`
552 may set a value when the field is set to ``NULL`` then there will also be
553 a "Default" section. (Note that many fields set on :c:data:`PyBaseObject_Type`
554 and :c:data:`PyType_Type` effectively act as defaults.)
555
556 .. c:member:: const char* PyTypeObject.tp_name
557
558 Pointer to a NUL-terminated string containing the name of the type. For types
559 that are accessible as module globals, the string should be the full module
560 name, followed by a dot, followed by the type name; for built-in types, it
561 should be just the type name. If the module is a submodule of a package, the
562 full package name is part of the full module name. For example, a type named
563 :class:`!T` defined in module :mod:`!M` in subpackage :mod:`!Q` in package :mod:`!P`
564 should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``.
565
566 For :ref:`dynamically allocated type objects <heap-types>`,
567 this should just be the type name, and
568 the module name explicitly stored in the type dict as the value for key
569 ``'__module__'``.
570
571 For :ref:`statically allocated type objects <static-types>`,
572 the *tp_name* field should contain a dot.
573 Everything before the last dot is made accessible as the :attr:`~type.__module__`
574 attribute, and everything after the last dot is made accessible as the
575 :attr:`~type.__name__` attribute.
576
577 If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the
578 :attr:`~type.__name__` attribute, and the :attr:`~type.__module__` attribute is undefined
579 (unless explicitly set in the dictionary, as explained above). This means your
580 type will be impossible to pickle. Additionally, it will not be listed in
581 module documentations created with pydoc.
582
583 This field must not be ``NULL``. It is the only required field
584 in :c:func:`PyTypeObject` (other than potentially
585 :c:member:`~PyTypeObject.tp_itemsize`).
586
587 **Inheritance:**
588
589 This field is not inherited by subtypes.
590
591
592 .. c:member:: Py_ssize_t PyTypeObject.tp_basicsize
593 Py_ssize_t PyTypeObject.tp_itemsize
594
595 These fields allow calculating the size in bytes of instances of the type.
596
597 There are two kinds of types: types with fixed-length instances have a zero
598 :c:member:`!tp_itemsize` field, types with variable-length instances have a non-zero
599 :c:member:`!tp_itemsize` field. For a type with fixed-length instances, all
600 instances have the same size, given in :c:member:`!tp_basicsize`.
601 (Exceptions to this rule can be made using
602 :c:func:`PyUnstable_Object_GC_NewWithExtraData`.)
603
604 For a type with variable-length instances, the instances must have an
605 :c:member:`~PyVarObject.ob_size` field, and the instance size is
606 :c:member:`!tp_basicsize` plus N times :c:member:`!tp_itemsize`,
607 where N is the "length" of the object.
608
609 Functions like :c:func:`PyObject_NewVar` will take the value of N as an
610 argument, and store in the instance's :c:member:`~PyVarObject.ob_size` field.
611 Note that the :c:member:`~PyVarObject.ob_size` field may later be used for
612 other purposes. For example, :py:type:`int` instances use the bits of
613 :c:member:`~PyVarObject.ob_size` in an implementation-defined
614 way; the underlying storage and its size should be accessed using
615 :c:func:`PyLong_Export`.
616
617 .. note::
618
619 The :c:member:`~PyVarObject.ob_size` field should be accessed using
620 the :c:func:`Py_SIZE()` and :c:func:`Py_SET_SIZE()` macros.
621
622 Also, the presence of an :c:member:`~PyVarObject.ob_size` field in the
623 instance layout doesn't mean that the instance structure is variable-length.
624 For example, the :py:type:`list` type has fixed-length instances, yet those
625 instances have a :c:member:`~PyVarObject.ob_size` field.
626 (As with :py:type:`int`, avoid reading lists' :c:member:`!ob_size` directly.
627 Call :c:func:`PyList_Size` instead.)
628
629 The :c:member:`!tp_basicsize` includes size needed for data of the type's
630 :c:member:`~PyTypeObject.tp_base`, plus any extra data needed
631 by each instance.
632
633 The correct way to set :c:member:`!tp_basicsize` is to use the
634 ``sizeof`` operator on the struct used to declare the instance layout.
635 This struct must include the struct used to declare the base type.
636 In other words, :c:member:`!tp_basicsize` must be greater than or equal
637 to the base's :c:member:`!tp_basicsize`.
638
639 Since every type is a subtype of :py:type:`object`, this struct must
640 include :c:type:`PyObject` or :c:type:`PyVarObject` (depending on
641 whether :c:member:`~PyVarObject.ob_size` should be included). These are
642 usually defined by the macro :c:macro:`PyObject_HEAD` or
643 :c:macro:`PyObject_VAR_HEAD`, respectively.
644
645 The basic size does not include the GC header size, as that header is not
646 part of :c:macro:`PyObject_HEAD`.
647
648 For cases where struct used to declare the base type is unknown,
649 see :c:member:`PyType_Spec.basicsize` and :c:func:`PyType_FromMetaclass`.
650
651 Notes about alignment:
652
653 - :c:member:`!tp_basicsize` must be a multiple of ``_Alignof(PyObject)``.
654 When using ``sizeof`` on a ``struct`` that includes
655 :c:macro:`PyObject_HEAD`, as recommended, the compiler ensures this.
656 When not using a C ``struct``, or when using compiler
657 extensions like ``__attribute__((packed))``, it is up to you.
658 - If the variable items require a particular alignment,
659 :c:member:`!tp_basicsize` and :c:member:`!tp_itemsize` must each be a
660 multiple of that alignment.
661 For example, if a type's variable part stores a ``double``, it is
662 your responsibility that both fields are a multiple of
663 ``_Alignof(double)``.
664
665 **Inheritance:**
666
667 These fields are inherited separately by subtypes.
668 (That is, if the field is set to zero, :c:func:`PyType_Ready` will copy
669 the value from the base type, indicating that the instances do not
670 need additional storage.)
671
672 If the base type has a non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to set
673 :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a subtype (though this
674 depends on the implementation of the base type).
675
676
677 .. c:member:: destructor PyTypeObject.tp_dealloc
678
679 .. corresponding-type-slot:: Py_tp_dealloc
680
681 A pointer to the instance destructor function. The function signature is::
682
683 void tp_dealloc(PyObject *self);
684
685 The destructor function should remove all references which the instance owns
686 (e.g., call :c:func:`Py_CLEAR`), free all memory buffers owned by the
687 instance, and call the type's :c:member:`~PyTypeObject.tp_free` function to
688 free the object itself.
689
690 If you may call functions that may set the error indicator, you must use
691 :c:func:`PyErr_GetRaisedException` and :c:func:`PyErr_SetRaisedException`
692 to ensure you don't clobber a preexisting error indicator (the deallocation
693 could have occurred while processing a different error):
694
695 .. code-block:: c
696
697 static void
698 foo_dealloc(foo_object *self)
699 {
700 PyObject *et, *ev, *etb;
701 PyObject *exc = PyErr_GetRaisedException();
702 ...
703 PyErr_SetRaisedException(exc);
704 }
705
706 The dealloc handler itself must not raise an exception; if it hits an error
707 case it should call :c:func:`PyErr_FormatUnraisable` to log (and clear) an
708 unraisable exception.
709
710 No guarantees are made about when an object is destroyed, except:
711
712 * Python will destroy an object immediately or some time after the final
713 reference to the object is deleted, unless its finalizer
714 (:c:member:`~PyTypeObject.tp_finalize`) subsequently resurrects the
715 object.
716 * An object will not be destroyed while it is being automatically finalized
717 (:c:member:`~PyTypeObject.tp_finalize`) or automatically cleared
718 (:c:member:`~PyTypeObject.tp_clear`).
719
720 CPython currently destroys an object immediately from :c:func:`Py_DECREF`
721 when the new reference count is zero, but this may change in a future
722 version.
723
724 It is recommended to call :c:func:`PyObject_CallFinalizerFromDealloc` at the
725 beginning of :c:member:`!tp_dealloc` to guarantee that the object is always
726 finalized before destruction.
727
728 If the type supports garbage collection (the :c:macro:`Py_TPFLAGS_HAVE_GC`
729 flag is set), the destructor should call :c:func:`PyObject_GC_UnTrack`
730 before clearing any member fields.
731
732 It is permissible to call :c:member:`~PyTypeObject.tp_clear` from
733 :c:member:`!tp_dealloc` to reduce code duplication and to guarantee that the
734 object is always cleared before destruction. Beware that
735 :c:member:`!tp_clear` might have already been called.
736
737 If the type is heap allocated (:c:macro:`Py_TPFLAGS_HEAPTYPE`), the
738 deallocator should release the owned reference to its type object (via
739 :c:func:`Py_DECREF`) after calling the type deallocator. See the example
740 code below.::
741
742 static void
743 foo_dealloc(PyObject *op)
744 {
745 foo_object *self = (foo_object *) op;
746 PyObject_GC_UnTrack(self);
747 Py_CLEAR(self->ref);
748 Py_TYPE(self)->tp_free(self);
749 }
750
751 :c:member:`!tp_dealloc` must leave the exception status unchanged. If it
752 needs to call something that might raise an exception, the exception state
753 must be backed up first and restored later (after logging any exceptions
754 with :c:func:`PyErr_WriteUnraisable`).
755
756 Example::
757
758 static void
759 foo_dealloc(PyObject *self)
760 {
761 PyObject *exc = PyErr_GetRaisedException();
762
763 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
764 // self was resurrected.
765 goto done;
766 }
767
768 PyTypeObject *tp = Py_TYPE(self);
769
770 if (tp->tp_flags & Py_TPFLAGS_HAVE_GC) {
771 PyObject_GC_UnTrack(self);
772 }
773
774 // Optional, but convenient to avoid code duplication.
775 if (tp->tp_clear && tp->tp_clear(self) < 0) {
776 PyErr_WriteUnraisable(self);
777 }
778
779 // Any additional destruction goes here.
780
781 tp->tp_free(self);
782 self = NULL; // In case PyErr_WriteUnraisable() is called below.
783
784 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) {
785 Py_CLEAR(tp);
786 }
787
788 done:
789 // Optional, if something was called that might have raised an
790 // exception.
791 if (PyErr_Occurred()) {
792 PyErr_WriteUnraisable(self);
793 }
794 PyErr_SetRaisedException(exc);
795 }
796
797 :c:member:`!tp_dealloc` may be called from
798 any Python thread, not just the thread which created the object (if the
799 object becomes part of a refcount cycle, that cycle might be collected by
800 a garbage collection on any thread). This is not a problem for Python
801 API calls, since the thread on which :c:member:`!tp_dealloc` is called
802 with an :term:`attached thread state`. However, if the object being
803 destroyed in turn destroys objects from some other C library, care
804 should be taken to ensure that destroying those objects on the thread
805 which called :c:member:`!tp_dealloc` will not violate any assumptions of
806 the library.
807
808
809 **Inheritance:**
810
811 This field is inherited by subtypes.
812
813 .. seealso::
814
815 :ref:`life-cycle` for details about how this slot relates to other slots.
816
817
818 .. c:member:: Py_ssize_t PyTypeObject.tp_vectorcall_offset
819
820 An optional offset to a per-instance function that implements calling
821 the object using the :ref:`vectorcall protocol <vectorcall>`,
822 a more efficient alternative
823 of the simpler :c:member:`~PyTypeObject.tp_call`.
824
825 This field is only used if the flag :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL`
826 is set. If so, this must be a positive integer containing the offset in the
827 instance of a :c:type:`vectorcallfunc` pointer.
828
829 The *vectorcallfunc* pointer may be ``NULL``, in which case the instance behaves
830 as if :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` was not set: calling the instance
831 falls back to :c:member:`~PyTypeObject.tp_call`.
832
833 Any class that sets ``Py_TPFLAGS_HAVE_VECTORCALL`` must also set
834 :c:member:`~PyTypeObject.tp_call` and make sure its behaviour is consistent
835 with the *vectorcallfunc* function.
836 This can be done by setting *tp_call* to :c:func:`PyVectorcall_Call`.
837
838 .. versionchanged:: 3.8
839
840 Before version 3.8, this slot was named ``tp_print``.
841 In Python 2.x, it was used for printing to a file.
842 In Python 3.0 to 3.7, it was unused.
843
844 .. versionchanged:: 3.12
845
846 Before version 3.12, it was not recommended for
847 :ref:`mutable heap types <heap-types>` to implement the vectorcall
848 protocol.
849 When a user sets :attr:`~object.__call__` in Python code, only *tp_call* is
850 updated, likely making it inconsistent with the vectorcall function.
851 Since 3.12, setting ``__call__`` will disable vectorcall optimization
852 by clearing the :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` flag.
853
854 **Inheritance:**
855
856 This field is always inherited.
857 However, the :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` flag is not
858 always inherited. If it's not set, then the subclass won't use
859 :ref:`vectorcall <vectorcall>`, except when
860 :c:func:`PyVectorcall_Call` is explicitly called.
861
862
863 .. c:member:: getattrfunc PyTypeObject.tp_getattr
864
865 .. corresponding-type-slot:: Py_tp_getattr
866
867 An optional pointer to the get-attribute-string function.
868
869 This field is deprecated. When it is defined, it should point to a function
870 that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string
871 instead of a Python string object to give the attribute name.
872
873 **Inheritance:**
874
875 Group: :c:member:`~PyTypeObject.tp_getattr`, :c:member:`~PyTypeObject.tp_getattro`
876
877 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype
878 inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
879 the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``.
880
881
882 .. c:member:: setattrfunc PyTypeObject.tp_setattr
883
884 .. corresponding-type-slot:: Py_tp_setattr
885
886 An optional pointer to the function for setting and deleting attributes.
887
888 This field is deprecated. When it is defined, it should point to a function
889 that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string
890 instead of a Python string object to give the attribute name.
891
892 **Inheritance:**
893
894 Group: :c:member:`~PyTypeObject.tp_setattr`, :c:member:`~PyTypeObject.tp_setattro`
895
896 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype
897 inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
898 the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``.
899
900
901 .. c:member:: PyAsyncMethods* PyTypeObject.tp_as_async
902
903 Pointer to an additional structure that contains fields relevant only to
904 objects which implement :term:`awaitable` and :term:`asynchronous iterator`
905 protocols at the C-level. See :ref:`async-structs` for details.
906
907 .. versionadded:: 3.5
908 Formerly known as ``tp_compare`` and ``tp_reserved``.
909
910 **Inheritance:**
911
912 The :c:member:`~PyTypeObject.tp_as_async` field is not inherited,
913 but the contained fields are inherited individually.
914
915
916 .. c:member:: reprfunc PyTypeObject.tp_repr
917
918 .. corresponding-type-slot:: Py_tp_repr
919
920 .. index:: pair: built-in function; repr
921
922 An optional pointer to a function that implements the built-in function
923 :func:`repr`.
924
925 The signature is the same as for :c:func:`PyObject_Repr`::
926
927 PyObject *tp_repr(PyObject *self);
928
929 The function must return a string or a Unicode object. Ideally,
930 this function should return a string that, when passed to
931 :func:`eval`, given a suitable environment, returns an object with the
932 same value. If this is not feasible, it should return a string starting with
933 ``'<'`` and ending with ``'>'`` from which both the type and the value of the
934 object can be deduced.
935
936 **Inheritance:**
937
938 This field is inherited by subtypes.
939
940 **Default:**
941
942 When this field is not set, a string of the form ``<%s object at %p>`` is
943 returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's
944 memory address.
945
946
947 .. c:member:: PyNumberMethods* PyTypeObject.tp_as_number
948
949 Pointer to an additional structure that contains fields relevant only to
950 objects which implement the number protocol. These fields are documented in
951 :ref:`number-structs`.
952
953 **Inheritance:**
954
955 The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the contained fields are
956 inherited individually.
957
958
959 .. c:member:: PySequenceMethods* PyTypeObject.tp_as_sequence
960
961 Pointer to an additional structure that contains fields relevant only to
962 objects which implement the sequence protocol. These fields are documented
963 in :ref:`sequence-structs`.
964
965 **Inheritance:**
966
967 The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the contained fields
968 are inherited individually.
969
970
971 .. c:member:: PyMappingMethods* PyTypeObject.tp_as_mapping
972
973 Pointer to an additional structure that contains fields relevant only to
974 objects which implement the mapping protocol. These fields are documented in
975 :ref:`mapping-structs`.
976
977 **Inheritance:**
978
979 The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the contained fields
980 are inherited individually.
981
982
983 .. c:member:: hashfunc PyTypeObject.tp_hash
984
985 .. corresponding-type-slot:: Py_tp_hash
986
987 .. index:: pair: built-in function; hash
988
989 An optional pointer to a function that implements the built-in function
990 :func:`hash`.
991
992 The signature is the same as for :c:func:`PyObject_Hash`::
993
994 Py_hash_t tp_hash(PyObject *);
995
996 The value ``-1`` should not be returned as a
997 normal return value; when an error occurs during the computation of the hash
998 value, the function should set an exception and return ``-1``.
999
1000 When this field is not set (*and* :c:member:`~PyTypeObject.tp_richcompare` is not set),
1001 an attempt to take the hash of the object raises :exc:`TypeError`.
1002 This is the same as setting it to :c:func:`PyObject_HashNotImplemented`.
1003
1004 This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to
1005 block inheritance of the hash method from a parent type. This is interpreted
1006 as the equivalent of ``__hash__ = None`` at the Python level, causing
1007 ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note
1008 that the converse is also true - setting ``__hash__ = None`` on a class at
1009 the Python level will result in the ``tp_hash`` slot being set to
1010 :c:func:`PyObject_HashNotImplemented`.
1011
1012 **Inheritance:**
1013
1014 Group: :c:member:`~PyTypeObject.tp_hash`, :c:member:`~PyTypeObject.tp_richcompare`
1015
1016 This field is inherited by subtypes together with
1017 :c:member:`~PyTypeObject.tp_richcompare`: a subtype inherits both of
1018 :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
1019 :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``.
1020
1021 **Default:**
1022
1023 :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericHash`.
1024
1025
1026 .. c:member:: ternaryfunc PyTypeObject.tp_call
1027
1028 .. corresponding-type-slot:: Py_tp_call
1029
1030 An optional pointer to a function that implements calling the object. This
1031 should be ``NULL`` if the object is not callable. The signature is the same as
1032 for :c:func:`PyObject_Call`::
1033
1034 PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);
1035
1036 **Inheritance:**
1037
1038 This field is inherited by subtypes.
1039
1040
1041 .. c:member:: reprfunc PyTypeObject.tp_str
1042
1043 .. corresponding-type-slot:: Py_tp_str
1044
1045 An optional pointer to a function that implements the built-in operation
1046 :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the
1047 constructor for that type. This constructor calls :c:func:`PyObject_Str` to do
1048 the actual work, and :c:func:`PyObject_Str` will call this handler.)
1049
1050 The signature is the same as for :c:func:`PyObject_Str`::
1051
1052 PyObject *tp_str(PyObject *self);
1053
1054 The function must return a string or a Unicode object. It should be a "friendly" string
1055 representation of the object, as this is the representation that will be used,
1056 among other things, by the :func:`print` function.
1057
1058 **Inheritance:**
1059
1060 This field is inherited by subtypes.
1061
1062 **Default:**
1063
1064 When this field is not set, :c:func:`PyObject_Repr` is called to return a string
1065 representation.
1066
1067
1068 .. c:member:: getattrofunc PyTypeObject.tp_getattro
1069
1070 .. corresponding-type-slot:: Py_tp_getattro
1071
1072 An optional pointer to the get-attribute function.
1073
1074 The signature is the same as for :c:func:`PyObject_GetAttr`::
1075
1076 PyObject *tp_getattro(PyObject *self, PyObject *attr);
1077
1078 It is usually convenient to set this field to :c:func:`PyObject_GenericGetAttr`,
1079 which implements the normal way of looking for object attributes.
1080
1081 **Inheritance:**
1082
1083 Group: :c:member:`~PyTypeObject.tp_getattr`, :c:member:`~PyTypeObject.tp_getattro`
1084
1085 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattr`: a subtype
1086 inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
1087 the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``.
1088
1089 **Default:**
1090
1091 :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`.
1092
1093
1094 .. c:member:: setattrofunc PyTypeObject.tp_setattro
1095
1096 .. corresponding-type-slot:: Py_tp_setattro
1097
1098 An optional pointer to the function for setting and deleting attributes.
1099
1100 The signature is the same as for :c:func:`PyObject_SetAttr`::
1101
1102 int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
1103
1104 In addition, setting *value* to ``NULL`` to delete an attribute must be
1105 supported. It is usually convenient to set this field to
1106 :c:func:`PyObject_GenericSetAttr`, which implements the normal
1107 way of setting object attributes.
1108
1109 **Inheritance:**
1110
1111 Group: :c:member:`~PyTypeObject.tp_setattr`, :c:member:`~PyTypeObject.tp_setattro`
1112
1113 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattr`: a subtype
1114 inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
1115 the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``.
1116
1117 **Default:**
1118
1119 :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`.
1120
1121
1122 .. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer
1123
1124 Pointer to an additional structure that contains fields relevant only to objects
1125 which implement the buffer interface. These fields are documented in
1126 :ref:`buffer-structs`.
1127
1128 **Inheritance:**
1129
1130 The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited,
1131 but the contained fields are inherited individually.
1132
1133
1134 .. c:member:: unsigned long PyTypeObject.tp_flags
1135
1136 This field is a bit mask of various flags. Some flags indicate variant
1137 semantics for certain situations; others are used to indicate that certain
1138 fields in the type object (or in the extension structures referenced via
1139 :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and
1140 :c:member:`~PyTypeObject.tp_as_buffer`) that were historically not always present are valid; if
1141 such a flag bit is clear, the type fields it guards must not be accessed and
1142 must be considered to have a zero or ``NULL`` value instead.
1143
1144 **Inheritance:**
1145
1146 Inheritance of this field is complicated. Most flag bits are inherited
1147 individually, i.e. if the base type has a flag bit set, the subtype inherits
1148 this flag bit. The flag bits that pertain to extension structures are strictly
1149 inherited if the extension structure is inherited, i.e. the base type's value of
1150 the flag bit is copied into the subtype together with a pointer to the extension
1151 structure. The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with
1152 the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the
1153 :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the
1154 :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have
1155 ``NULL`` values.
1156
1157 .. XXX are most flag bits *really* inherited individually?
1158
1159 **Default:**
1160
1161 :c:data:`PyBaseObject_Type` uses
1162 ``Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE``.
1163
1164 **Bit Masks:**
1165
1166 .. c:namespace:: NULL
1167
1168 The following bit masks are currently defined; these can be ORed together using
1169 the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field. The macro
1170 :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
1171 checks whether ``tp->tp_flags & f`` is non-zero.
1172
1173 .. c:macro:: Py_TPFLAGS_HEAPTYPE
1174
1175 This bit is set when the type object itself is allocated on the heap, for
1176 example, types created dynamically using :c:func:`PyType_FromSpec`. In this
1177 case, the :c:member:`~PyObject.ob_type` field of its instances is considered a reference to
1178 the type, and the type object is INCREF'ed when a new instance is created, and
1179 DECREF'ed when an instance is destroyed (this does not apply to instances of
1180 subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
1181 DECREF'ed). Heap types should also :ref:`support garbage collection <supporting-cycle-detection>`
1182 as they can form a reference cycle with their own module object.
1183
1184 **Inheritance:**
1185
1186 ???
1187
1188
1189 .. c:macro:: Py_TPFLAGS_BASETYPE
1190
1191 This bit is set when the type can be used as the base type of another type. If
1192 this bit is clear, the type cannot be subtyped (similar to a "final" class in
1193 Java).
1194
1195 **Inheritance:**
1196
1197 ???
1198
1199
1200 .. c:macro:: Py_TPFLAGS_READY
1201
1202 This bit is set when the type object has been fully initialized by
1203 :c:func:`PyType_Ready`.
1204
1205 **Inheritance:**
1206
1207 ???
1208
1209
1210 .. c:macro:: Py_TPFLAGS_READYING
1211
1212 This bit is set while :c:func:`PyType_Ready` is in the process of initializing
1213 the type object.
1214
1215 **Inheritance:**
1216
1217 ???
1218
1219
1220 .. c:macro:: Py_TPFLAGS_HAVE_GC
1221
1222 This bit is set when the object supports garbage collection. If this bit
1223 is set, memory for new instances (see :c:member:`~PyTypeObject.tp_alloc`)
1224 must be allocated using :c:macro:`PyObject_GC_New` or
1225 :c:func:`PyType_GenericAlloc` and deallocated (see
1226 :c:member:`~PyTypeObject.tp_free`) using :c:func:`PyObject_GC_Del`. More
1227 information in section :ref:`supporting-cycle-detection`.
1228
1229 **Inheritance:**
1230
1231 Group: :c:macro:`Py_TPFLAGS_HAVE_GC`, :c:member:`~PyTypeObject.tp_traverse`, :c:member:`~PyTypeObject.tp_clear`
1232
1233 The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited
1234 together with the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear`
1235 fields, i.e. if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is
1236 clear in the subtype and the :c:member:`~PyTypeObject.tp_traverse` and
1237 :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have ``NULL``
1238 values.
1239
1240
1241 .. c:macro:: Py_TPFLAGS_DEFAULT
1242
1243 This is a bitmask of all the bits that pertain to the existence of certain
1244 fields in the type object and its extension structures. Currently, it includes
1245 the following bits: :c:macro:`Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`.
1246
1247 **Inheritance:**
1248
1249 ???
1250
1251
1252 .. c:macro:: Py_TPFLAGS_METHOD_DESCRIPTOR
1253
1254 This bit indicates that objects behave like unbound methods.
1255
1256 If this flag is set for ``type(meth)``, then:
1257
1258 - ``meth.__get__(obj, cls)(*args, **kwds)`` (with ``obj`` not None)
1259 must be equivalent to ``meth(obj, *args, **kwds)``.
1260
1261 - ``meth.__get__(None, cls)(*args, **kwds)``
1262 must be equivalent to ``meth(*args, **kwds)``.
1263
1264 This flag enables an optimization for typical method calls like
1265 ``obj.meth()``: it avoids creating a temporary "bound method" object for
1266 ``obj.meth``.
1267
1268 .. versionadded:: 3.8
1269
1270 **Inheritance:**
1271
1272 This flag is never inherited by types without the
1273 :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` flag set. For extension types, it is
1274 inherited whenever :c:member:`~PyTypeObject.tp_descr_get` is inherited.
1275
1276 .. c:macro:: Py_TPFLAGS_MANAGED_DICT
1277
1278 This bit indicates that instances of the class have a :attr:`~object.__dict__`
1279 attribute, and that the space for the dictionary is managed by the VM.
1280
1281 If this flag is set, :c:macro:`Py_TPFLAGS_HAVE_GC` should also be set.
1282
1283 The type traverse function must call :c:func:`PyObject_VisitManagedDict`
1284 and its clear function must call :c:func:`PyObject_ClearManagedDict`.
1285
1286 .. versionadded:: 3.12
1287
1288 **Inheritance:**
1289
1290 This flag is inherited unless the
1291 :c:member:`~PyTypeObject.tp_dictoffset` field is set in a superclass.
1292
1293
1294 .. c:macro:: Py_TPFLAGS_MANAGED_WEAKREF
1295
1296 This bit indicates that instances of the class should be weakly
1297 referenceable.
1298
1299 .. versionadded:: 3.12
1300
1301 **Inheritance:**
1302
1303 This flag is inherited unless the
1304 :c:member:`~PyTypeObject.tp_weaklistoffset` field is set in a superclass.
1305
1306
1307 .. c:macro:: Py_TPFLAGS_ITEMS_AT_END
1308
1309 Only usable with variable-size types, i.e. ones with non-zero
1310 :c:member:`~PyTypeObject.tp_itemsize`.
1311
1312 Indicates that the variable-sized portion of an instance of this type is
1313 at the end of the instance's memory area, at an offset of
1314 ``Py_TYPE(obj)->tp_basicsize`` (which may be different in each
1315 subclass).
1316
1317 When setting this flag, be sure that all superclasses either
1318 use this memory layout, or are not variable-sized.
1319 Python does not check this.
1320
1321 .. versionadded:: 3.12
1322
1323 **Inheritance:**
1324
1325 This flag is inherited.
1326
1327 .. XXX Document more flags here?
1328
1329
1330 .. c:macro:: Py_TPFLAGS_LONG_SUBCLASS
1331 .. c:macro:: Py_TPFLAGS_LIST_SUBCLASS
1332 .. c:macro:: Py_TPFLAGS_TUPLE_SUBCLASS
1333 .. c:macro:: Py_TPFLAGS_BYTES_SUBCLASS
1334 .. c:macro:: Py_TPFLAGS_UNICODE_SUBCLASS
1335 .. c:macro:: Py_TPFLAGS_DICT_SUBCLASS
1336 .. c:macro:: Py_TPFLAGS_BASE_EXC_SUBCLASS
1337 .. c:macro:: Py_TPFLAGS_TYPE_SUBCLASS
1338
1339 Functions such as :c:func:`PyLong_Check` will call :c:func:`PyType_FastSubclass`
1340 with one of these flags to quickly determine if a type is a subclass
1341 of a built-in type; such specific checks are faster than a generic
1342 check, like :c:func:`PyObject_IsInstance`. Custom types that inherit
1343 from built-ins should have their :c:member:`~PyTypeObject.tp_flags`
1344 set appropriately, or the code that interacts with such types
1345 will behave differently depending on what kind of check is used.
1346
1347
1348 .. c:macro:: Py_TPFLAGS_HAVE_FINALIZE
1349
1350 This bit is set when the :c:member:`~PyTypeObject.tp_finalize` slot is present in the
1351 type structure.
1352
1353 .. versionadded:: 3.4
1354
1355 .. deprecated:: 3.8
1356 This flag isn't necessary anymore, as the interpreter assumes the
1357 :c:member:`~PyTypeObject.tp_finalize` slot is always present in the
1358 type structure.
1359
1360
1361 .. c:macro:: _Py_TPFLAGS_HAVE_VECTORCALL
1362 :no-typesetting:
1363
1364 .. c:macro:: Py_TPFLAGS_HAVE_VECTORCALL
1365
1366 This bit is set when the class implements
1367 the :ref:`vectorcall protocol <vectorcall>`.
1368 See :c:member:`~PyTypeObject.tp_vectorcall_offset` for details.
1369
1370 **Inheritance:**
1371
1372 This bit is inherited if :c:member:`~PyTypeObject.tp_call` is also
1373 inherited.
1374
1375 .. versionadded:: 3.8 as ``_Py_TPFLAGS_HAVE_VECTORCALL``
1376
1377 .. versionchanged:: 3.9
1378
1379 Renamed to the current name, without the leading underscore.
1380 The old provisional name is :term:`soft deprecated`.
1381
1382 .. versionchanged:: 3.12
1383
1384 This flag is now removed from a class when the class's
1385 :py:meth:`~object.__call__` method is reassigned.
1386
1387 This flag can now be inherited by mutable classes.
1388
1389 .. c:macro:: Py_TPFLAGS_IMMUTABLETYPE
1390
1391 This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.
1392
1393 :c:func:`PyType_Ready` automatically applies this flag to
1394 :ref:`static types <static-types>`.
1395
1396 **Inheritance:**
1397
1398 This flag is not inherited.
1399
1400 .. versionadded:: 3.10
1401
1402 .. c:macro:: Py_TPFLAGS_DISALLOW_INSTANTIATION
1403
1404 Disallow creating instances of the type: set
1405 :c:member:`~PyTypeObject.tp_new` to NULL and don't create the ``__new__``
1406 key in the type dictionary.
1407
1408 The flag must be set before creating the type, not after. For example, it
1409 must be set before :c:func:`PyType_Ready` is called on the type.
1410
1411 The flag is set automatically on :ref:`static types <static-types>` if
1412 :c:member:`~PyTypeObject.tp_base` is NULL or ``&PyBaseObject_Type`` and
1413 :c:member:`~PyTypeObject.tp_new` is NULL.
1414
1415 **Inheritance:**
1416
1417 This flag is not inherited.
1418 However, subclasses will not be instantiable unless they provide a
1419 non-NULL :c:member:`~PyTypeObject.tp_new` (which is only possible
1420 via the C API).
1421
1422 .. note::
1423
1424 To disallow instantiating a class directly but allow instantiating
1425 its subclasses (e.g. for an :term:`abstract base class`),
1426 do not use this flag.
1427 Instead, make :c:member:`~PyTypeObject.tp_new` only succeed for
1428 subclasses.
1429
1430 .. versionadded:: 3.10
1431
1432
1433 .. c:macro:: Py_TPFLAGS_MAPPING
1434
1435 This bit indicates that instances of the class may match mapping patterns
1436 when used as the subject of a :keyword:`match` block. It is automatically
1437 set when registering or subclassing :class:`collections.abc.Mapping`, and
1438 unset when registering :class:`collections.abc.Sequence`.
1439
1440 .. note::
1441
1442 :c:macro:`Py_TPFLAGS_MAPPING` and :c:macro:`Py_TPFLAGS_SEQUENCE` are
1443 mutually exclusive; it is an error to enable both flags simultaneously.
1444
1445 **Inheritance:**
1446
1447 This flag is inherited by types that do not already set
1448 :c:macro:`Py_TPFLAGS_SEQUENCE`.
1449
1450 .. seealso:: :pep:`634` -- Structural Pattern Matching: Specification
1451
1452 .. versionadded:: 3.10
1453
1454
1455 .. c:macro:: Py_TPFLAGS_SEQUENCE
1456
1457 This bit indicates that instances of the class may match sequence patterns
1458 when used as the subject of a :keyword:`match` block. It is automatically
1459 set when registering or subclassing :class:`collections.abc.Sequence`, and
1460 unset when registering :class:`collections.abc.Mapping`.
1461
1462 .. note::
1463
1464 :c:macro:`Py_TPFLAGS_MAPPING` and :c:macro:`Py_TPFLAGS_SEQUENCE` are
1465 mutually exclusive; it is an error to enable both flags simultaneously.
1466
1467 **Inheritance:**
1468
1469 This flag is inherited by types that do not already set
1470 :c:macro:`Py_TPFLAGS_MAPPING`.
1471
1472 .. seealso:: :pep:`634` -- Structural Pattern Matching: Specification
1473
1474 .. versionadded:: 3.10
1475
1476
1477 .. c:macro:: Py_TPFLAGS_VALID_VERSION_TAG
1478
1479 Internal. Do not set or unset this flag.
1480 To indicate that a class has changed call :c:func:`PyType_Modified`
1481
1482 .. warning::
1483 This flag is present in header files, but is not be used.
1484 It will be removed in a future version of CPython
1485
1486
1487 .. c:macro:: Py_TPFLAGS_HAVE_VERSION_TAG
1488
1489 This is a :term:`soft deprecated` macro that does nothing.
1490 Historically, this would indicate that the
1491 :c:member:`~PyTypeObject.tp_version_tag` field was available and
1492 initialized.
1493
1494
1495 .. c:macro:: Py_TPFLAGS_INLINE_VALUES
1496
1497 This bit indicates that instances of this type will have an "inline values"
1498 array (containing the object's attributes) placed directly after the end
1499 of the object.
1500
1501 This requires that :c:macro:`Py_TPFLAGS_HAVE_GC` is set.
1502
1503 **Inheritance:**
1504
1505 This flag is not inherited.
1506
1507 .. versionadded:: 3.13
1508
1509
1510 .. c:macro:: Py_TPFLAGS_IS_ABSTRACT
1511
1512 This bit indicates that this is an abstract type and therefore cannot
1513 be instantiated.
1514
1515 **Inheritance:**
1516
1517 This flag is not inherited.
1518
1519 .. seealso::
1520 :mod:`abc`
1521
1522
1523 .. c:macro:: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION
1524
1525 Internal. Do not set or unset this flag.
1526 Historically, this was a reserved flag for use in Stackless Python.
1527
1528 .. warning::
1529 This flag is present in header files, but is not be used.
1530 This may be removed in a future version of CPython.
1531
1532
1533 .. c:member:: const char* PyTypeObject.tp_doc
1534
1535 .. corresponding-type-slot:: Py_tp_doc
1536
1537 An optional pointer to a NUL-terminated C string giving the docstring for this
1538 type object. This is exposed as the :attr:`~type.__doc__` attribute on the
1539 type and instances of the type.
1540
1541 **Inheritance:**
1542
1543 This field is *not* inherited by subtypes.
1544
1545
1546 .. c:member:: traverseproc PyTypeObject.tp_traverse
1547
1548 .. corresponding-type-slot:: Py_tp_traverse
1549
1550 An optional pointer to a traversal function for the garbage collector. This is
1551 only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The signature is::
1552
1553 int tp_traverse(PyObject *self, visitproc visit, void *arg);
1554
1555 More information about Python's garbage collection scheme can be found
1556 in section :ref:`supporting-cycle-detection`.
1557
1558 The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
1559 reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
1560 simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
1561 objects that the instance owns. For example, this is function :c:func:`!local_traverse` from the
1562 :mod:`!_thread` extension module::
1563
1564 static int
1565 local_traverse(PyObject *op, visitproc visit, void *arg)
1566 {
1567 localobject *self = (localobject *) op;
1568 Py_VISIT(self->args);
1569 Py_VISIT(self->kw);
1570 Py_VISIT(self->dict);
1571 return 0;
1572 }
1573
1574 Note that :c:func:`Py_VISIT` is called only on those members that can participate
1575 in reference cycles. Although there is also a ``self->key`` member, it can only
1576 be ``NULL`` or a Python string and therefore cannot be part of a reference cycle.
1577
1578 On the other hand, even if you know a member can never be part of a cycle, as a
1579 debugging aid you may want to visit it anyway just so the :mod:`gc` module's
1580 :func:`~gc.get_referents` function will include it.
1581
1582 Heap types (:c:macro:`Py_TPFLAGS_HEAPTYPE`) must visit their type with::
1583
1584 Py_VISIT(Py_TYPE(self));
1585
1586 It is only needed since Python 3.9. To support Python 3.8 and older, this
1587 line must be conditional::
1588
1589 #if PY_VERSION_HEX >= 0x03090000
1590 Py_VISIT(Py_TYPE(self));
1591 #endif
1592
1593 If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the
1594 :c:member:`~PyTypeObject.tp_flags` field, the traverse function must call
1595 :c:func:`PyObject_VisitManagedDict` like this::
1596
1597 PyObject_VisitManagedDict((PyObject*)self, visit, arg);
1598
1599 .. warning::
1600 When implementing :c:member:`~PyTypeObject.tp_traverse`, only the
1601 members that the instance *owns* (by having :term:`strong references
1602 <strong reference>` to them) must be
1603 visited. For instance, if an object supports weak references via the
1604 :c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
1605 the linked list (what *tp_weaklist* points to) must **not** be
1606 visited as the instance does not directly own the weak references to itself
1607 (the weakreference list is there to support the weak reference machinery,
1608 but the instance has no strong reference to the elements inside it, as they
1609 are allowed to be removed even if the instance is still alive).
1610
1611 .. warning::
1612 The traversal function must not have any side effects. It must not
1613 modify the reference counts of any Python objects nor create or destroy
1614 any Python objects.
1615
1616 Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
1617 :c:func:`!local_traverse` to have these specific names; don't name them just
1618 anything.
1619
1620 Instances of :ref:`heap-allocated types <heap-types>` hold a reference to
1621 their type. Their traversal function must therefore either visit
1622 :c:func:`Py_TYPE(self) <Py_TYPE>`, or delegate this responsibility by
1623 calling ``tp_traverse`` of another heap-allocated type (such as a
1624 heap-allocated superclass).
1625 If they do not, the type object may not be garbage-collected.
1626
1627 .. note::
1628
1629 The :c:member:`~PyTypeObject.tp_traverse` function can be called from any
1630 thread.
1631
1632 .. versionchanged:: 3.9
1633
1634 Heap-allocated types are expected to visit ``Py_TYPE(self)`` in
1635 ``tp_traverse``. In earlier versions of Python, due to
1636 `bug 40217 <https://bugs.python.org/issue40217>`_, doing this
1637 may lead to crashes in subclasses.
1638
1639 **Inheritance:**
1640
1641 Group: :c:macro:`Py_TPFLAGS_HAVE_GC`, :c:member:`~PyTypeObject.tp_traverse`, :c:member:`~PyTypeObject.tp_clear`
1642
1643 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_clear` and the
1644 :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
1645 :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
1646 the subtype.
1647
1648
1649 .. c:member:: inquiry PyTypeObject.tp_clear
1650
1651 .. corresponding-type-slot:: Py_tp_clear
1652
1653 An optional pointer to a clear function. The signature is::
1654
1655 int tp_clear(PyObject *);
1656
1657 The purpose of this function is to break reference cycles that are causing a
1658 :term:`cyclic isolate` so that the objects can be safely destroyed. A
1659 cleared object is a partially destroyed object; the object is not obligated
1660 to satisfy design invariants held during normal use.
1661
1662 :c:member:`!tp_clear` does not need to delete references to objects that
1663 can't participate in reference cycles, such as Python strings or Python
1664 integers. However, it may be convenient to clear all references, and write
1665 the type's :c:member:`~PyTypeObject.tp_dealloc` function to invoke
1666 :c:member:`!tp_clear` to avoid code duplication. (Beware that
1667 :c:member:`!tp_clear` might have already been called. Prefer calling
1668 idempotent functions like :c:func:`Py_CLEAR`.)
1669
1670 Any non-trivial cleanup should be performed in
1671 :c:member:`~PyTypeObject.tp_finalize` instead of :c:member:`!tp_clear`.
1672
1673 .. note::
1674
1675 If :c:member:`!tp_clear` fails to break a reference cycle then the
1676 objects in the :term:`cyclic isolate` may remain indefinitely
1677 uncollectable ("leak"). See :data:`gc.garbage`.
1678
1679 .. note::
1680
1681 Referents (direct and indirect) might have already been cleared; they are
1682 not guaranteed to be in a consistent state.
1683
1684 .. note::
1685
1686 The :c:member:`~PyTypeObject.tp_clear` function can be called from any
1687 thread.
1688
1689 .. note::
1690
1691 An object is not guaranteed to be automatically cleared before its
1692 destructor (:c:member:`~PyTypeObject.tp_dealloc`) is called.
1693
1694 This function differs from the destructor
1695 (:c:member:`~PyTypeObject.tp_dealloc`) in the following ways:
1696
1697 * The purpose of clearing an object is to remove references to other objects
1698 that might participate in a reference cycle. The purpose of the
1699 destructor, on the other hand, is a superset: it must release *all*
1700 resources it owns, including references to objects that cannot participate
1701 in a reference cycle (e.g., integers) as well as the object's own memory
1702 (by calling :c:member:`~PyTypeObject.tp_free`).
1703 * When :c:member:`!tp_clear` is called, other objects might still hold
1704 references to the object being cleared. Because of this,
1705 :c:member:`!tp_clear` must not deallocate the object's own memory
1706 (:c:member:`~PyTypeObject.tp_free`). The destructor, on the other hand,
1707 is only called when no (strong) references exist, and as such, must
1708 safely destroy the object itself by deallocating it.
1709 * :c:member:`!tp_clear` might never be automatically called. An object's
1710 destructor, on the other hand, will be automatically called some time
1711 after the object becomes unreachable (i.e., either there are no references
1712 to the object or the object is a member of a :term:`cyclic isolate`).
1713
1714 No guarantees are made about when, if, or how often Python automatically
1715 clears an object, except:
1716
1717 * Python will not automatically clear an object if it is reachable, i.e.,
1718 there is a reference to it and it is not a member of a :term:`cyclic
1719 isolate`.
1720 * Python will not automatically clear an object if it has not been
1721 automatically finalized (see :c:member:`~PyTypeObject.tp_finalize`). (If
1722 the finalizer resurrected the object, the object may or may not be
1723 automatically finalized again before it is cleared.)
1724 * If an object is a member of a :term:`cyclic isolate`, Python will not
1725 automatically clear it if any member of the cyclic isolate has not yet
1726 been automatically finalized (:c:member:`~PyTypeObject.tp_finalize`).
1727 * Python will not destroy an object until after any automatic calls to its
1728 :c:member:`!tp_clear` function have returned. This ensures that the act
1729 of breaking a reference cycle does not invalidate the ``self`` pointer
1730 while :c:member:`!tp_clear` is still executing.
1731 * Python will not automatically call :c:member:`!tp_clear` multiple times
1732 concurrently.
1733
1734 CPython currently only automatically clears objects as needed to break
1735 reference cycles in a :term:`cyclic isolate`, but future versions might
1736 clear objects regularly before their destruction.
1737
1738 Taken together, all :c:member:`~PyTypeObject.tp_clear` functions in the
1739 system must combine to break all reference cycles. This is subtle, and if
1740 in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function. For
1741 example, the tuple type does not implement a
1742 :c:member:`~PyTypeObject.tp_clear` function, because it's possible to prove
1743 that no reference cycle can be composed entirely of tuples. Therefore the
1744 :c:member:`~PyTypeObject.tp_clear` functions of other types are responsible
1745 for breaking any cycle containing a tuple. This isn't immediately obvious,
1746 and there's rarely a good reason to avoid implementing
1747 :c:member:`~PyTypeObject.tp_clear`.
1748
1749 Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the instance's references to
1750 those of its members that may be Python objects, and set its pointers to those
1751 members to ``NULL``, as in the following example::
1752
1753 static int
1754 local_clear(PyObject *op)
1755 {
1756 localobject *self = (localobject *) op;
1757 Py_CLEAR(self->key);
1758 Py_CLEAR(self->args);
1759 Py_CLEAR(self->kw);
1760 Py_CLEAR(self->dict);
1761 return 0;
1762 }
1763
1764 The :c:func:`Py_CLEAR` macro should be used, because clearing references is
1765 delicate: the reference to the contained object must not be released
1766 (via :c:func:`Py_DECREF`) until
1767 after the pointer to the contained object is set to ``NULL``. This is because
1768 releasing the reference may cause the contained object to become trash,
1769 triggering a chain of reclamation activity that may include invoking arbitrary
1770 Python code (due to finalizers, or weakref callbacks, associated with the
1771 contained object). If it's possible for such code to reference *self* again,
1772 it's important that the pointer to the contained object be ``NULL`` at that time,
1773 so that *self* knows the contained object can no longer be used. The
1774 :c:func:`Py_CLEAR` macro performs the operations in a safe order.
1775
1776 If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the
1777 :c:member:`~PyTypeObject.tp_flags` field, the clear function must call
1778 :c:func:`PyObject_ClearManagedDict` like this::
1779
1780 PyObject_ClearManagedDict((PyObject*)self);
1781
1782 More information about Python's garbage collection scheme can be found in
1783 section :ref:`supporting-cycle-detection`.
1784
1785 **Inheritance:**
1786
1787 Group: :c:macro:`Py_TPFLAGS_HAVE_GC`, :c:member:`~PyTypeObject.tp_traverse`, :c:member:`~PyTypeObject.tp_clear`
1788
1789 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_traverse` and the
1790 :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
1791 :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
1792 the subtype.
1793
1794 .. seealso::
1795
1796 :ref:`life-cycle` for details about how this slot relates to other slots.
1797
1798
1799 .. c:member:: richcmpfunc PyTypeObject.tp_richcompare
1800
1801 .. corresponding-type-slot:: Py_tp_richcompare
1802
1803 An optional pointer to the rich comparison function, whose signature is::
1804
1805 PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
1806
1807 The first parameter is guaranteed to be an instance of the type
1808 that is defined by :c:type:`PyTypeObject`.
1809
1810 The function should return the result of the comparison (usually ``Py_True``
1811 or ``Py_False``). If the comparison is undefined, it must return
1812 ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and
1813 set an exception condition.
1814
1815 The following constants are defined to be used as the third argument for
1816 :c:member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:
1817
1818 .. c:namespace:: NULL
1819
1820 +--------------------+------------+
1821 | Constant | Comparison |
1822 +====================+============+
1823 | .. c:macro:: Py_LT | ``<`` |
1824 +--------------------+------------+
1825 | .. c:macro:: Py_LE | ``<=`` |
1826 +--------------------+------------+
1827 | .. c:macro:: Py_EQ | ``==`` |
1828 +--------------------+------------+
1829 | .. c:macro:: Py_NE | ``!=`` |
1830 +--------------------+------------+
1831 | .. c:macro:: Py_GT | ``>`` |
1832 +--------------------+------------+
1833 | .. c:macro:: Py_GE | ``>=`` |
1834 +--------------------+------------+
1835
1836 The following macro is defined to ease writing rich comparison functions:
1837
1838 .. c:macro:: Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
1839
1840 Return ``Py_True`` or ``Py_False`` from the function, depending on the
1841 result of a comparison.
1842 VAL_A and VAL_B must be orderable by C comparison operators (for example,
1843 they may be C ints or floats). The third argument specifies the requested
1844 operation, as for :c:func:`PyObject_RichCompare`.
1845
1846 The returned value is a new :term:`strong reference`.
1847
1848 On error, sets an exception and returns ``NULL`` from the function.
1849
1850 .. versionadded:: 3.7
1851
1852 **Inheritance:**
1853
1854 Group: :c:member:`~PyTypeObject.tp_hash`, :c:member:`~PyTypeObject.tp_richcompare`
1855
1856 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_hash`:
1857 a subtype inherits :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` when
1858 the subtype's :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both
1859 ``NULL``.
1860
1861 **Default:**
1862
1863 :c:data:`PyBaseObject_Type` provides a :c:member:`~PyTypeObject.tp_richcompare`
1864 implementation, which may be inherited. However, if only
1865 :c:member:`~PyTypeObject.tp_hash` is defined, not even the inherited function is used
1866 and instances of the type will not be able to participate in any
1867 comparisons.
1868
1869
1870 .. c:member:: Py_ssize_t PyTypeObject.tp_weaklistoffset
1871
1872 While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF`
1873 should be used instead, if at all possible.
1874
1875 If the instances of this type are weakly referenceable, this field is greater
1876 than zero and contains the offset in the instance structure of the weak
1877 reference list head (ignoring the GC header, if present); this offset is used by
1878 :c:func:`PyObject_ClearWeakRefs` and the ``PyWeakref_*`` functions. The
1879 instance structure needs to include a field of type :c:expr:`PyObject*` which is
1880 initialized to ``NULL``.
1881
1882 Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that is the list head for
1883 weak references to the type object itself.
1884
1885 It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit and
1886 :c:member:`~PyTypeObject.tp_weaklistoffset`.
1887
1888 **Inheritance:**
1889
1890 This field is inherited by subtypes, but see the rules listed below. A subtype
1891 may override this offset; this means that the subtype uses a different weak
1892 reference list head than the base type. Since the list head is always found via
1893 :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem.
1894
1895 **Default:**
1896
1897 If the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit is set in the
1898 :c:member:`~PyTypeObject.tp_flags` field, then
1899 :c:member:`~PyTypeObject.tp_weaklistoffset` will be set to a negative value,
1900 to indicate that it is unsafe to use this field.
1901
1902
1903 .. c:member:: getiterfunc PyTypeObject.tp_iter
1904
1905 .. corresponding-type-slot:: Py_tp_iter
1906
1907 An optional pointer to a function that returns an :term:`iterator` for the
1908 object. Its presence normally signals that the instances of this type are
1909 :term:`iterable` (although sequences may be iterable without this function).
1910
1911 This function has the same signature as :c:func:`PyObject_GetIter`::
1912
1913 PyObject *tp_iter(PyObject *self);
1914
1915 **Inheritance:**
1916
1917 This field is inherited by subtypes.
1918
1919
1920 .. c:member:: iternextfunc PyTypeObject.tp_iternext
1921
1922 .. corresponding-type-slot:: Py_tp_iternext
1923
1924 An optional pointer to a function that returns the next item in an
1925 :term:`iterator`. The signature is::
1926
1927 PyObject *tp_iternext(PyObject *self);
1928
1929 When the iterator is exhausted, it must return ``NULL``; a :exc:`StopIteration`
1930 exception may or may not be set. When another error occurs, it must return
1931 ``NULL`` too. Its presence signals that the instances of this type are
1932 iterators.
1933
1934 Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` function, and that
1935 function should return the iterator instance itself (not a new iterator
1936 instance).
1937
1938 This function has the same signature as :c:func:`PyIter_Next`.
1939
1940 **Inheritance:**
1941
1942 This field is inherited by subtypes.
1943
1944
1945 .. c:member:: struct PyMethodDef* PyTypeObject.tp_methods
1946
1947 .. corresponding-type-slot:: Py_tp_methods
1948
1949 An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMethodDef`
1950 structures, declaring regular methods of this type.
1951
1952 For each entry in the array, an entry is added to the type's dictionary (see
1953 :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor.
1954
1955 **Inheritance:**
1956
1957 This field is not inherited by subtypes (methods are inherited through a
1958 different mechanism).
1959
1960
1961 .. c:member:: struct PyMemberDef* PyTypeObject.tp_members
1962
1963 .. corresponding-type-slot:: Py_tp_members
1964
1965 An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMemberDef`
1966 structures, declaring regular data members (fields or slots) of instances of
1967 this type.
1968
1969 For each entry in the array, an entry is added to the type's dictionary (see
1970 :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor.
1971
1972 **Inheritance:**
1973
1974 This field is not inherited by subtypes (members are inherited through a
1975 different mechanism).
1976
1977
1978 .. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset
1979
1980 .. corresponding-type-slot:: Py_tp_getset
1981
1982 An optional pointer to a static ``NULL``-terminated array of :c:type:`PyGetSetDef`
1983 structures, declaring computed attributes of instances of this type.
1984
1985 For each entry in the array, an entry is added to the type's dictionary (see
1986 :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor.
1987
1988 **Inheritance:**
1989
1990 This field is not inherited by subtypes (computed attributes are inherited
1991 through a different mechanism).
1992
1993
1994 .. c:member:: PyTypeObject* PyTypeObject.tp_base
1995
1996 .. corresponding-type-slot:: Py_tp_base
1997
1998 An optional pointer to a base type from which type properties are inherited. At
1999 this level, only single inheritance is supported; multiple inheritance require
2000 dynamically creating a type object by calling the metatype.
2001
2002 .. note::
2003
2004 .. from Modules/xxmodule.c
2005
2006 Slot initialization is subject to the rules of initializing globals.
2007 C99 requires the initializers to be "address constants". Function
2008 designators like :c:func:`PyType_GenericNew`, with implicit conversion
2009 to a pointer, are valid C99 address constants.
2010
2011 However, the unary '&' operator applied to a non-static variable
2012 like :c:data:`PyBaseObject_Type` is not required to produce an address
2013 constant. Compilers may support this (gcc does), MSVC does not.
2014 Both compilers are strictly standard conforming in this particular
2015 behavior.
2016
2017 Consequently, :c:member:`~PyTypeObject.tp_base` should be set in
2018 the extension module's init function.
2019
2020 **Inheritance:**
2021
2022 This field is not inherited by subtypes (obviously).
2023
2024 **Default:**
2025
2026 This field defaults to ``&PyBaseObject_Type`` (which to Python
2027 programmers is known as the type :class:`object`).
2028
2029
2030 .. c:member:: PyObject* PyTypeObject.tp_dict
2031
2032 The type's dictionary is stored here by :c:func:`PyType_Ready`.
2033
2034 This field should normally be initialized to ``NULL`` before PyType_Ready is
2035 called; it may also be initialized to a dictionary containing initial attributes
2036 for the type. Once :c:func:`PyType_Ready` has initialized the type, extra
2037 attributes for the type may be added to this dictionary only if they don't
2038 correspond to overloaded operations (like :meth:`~object.__add__`). Once
2039 initialization for the type has finished, this field should be
2040 treated as read-only.
2041
2042 Some types may not store their dictionary in this slot.
2043 Use :c:func:`PyType_GetDict` to retrieve the dictionary for an arbitrary
2044 type.
2045
2046 .. versionchanged:: 3.12
2047
2048 Internals detail: For static builtin types, this is always ``NULL``.
2049 Instead, the dict for such types is stored on ``PyInterpreterState``.
2050 Use :c:func:`PyType_GetDict` to get the dict for an arbitrary type.
2051
2052 **Inheritance:**
2053
2054 This field is not inherited by subtypes (though the attributes defined in here
2055 are inherited through a different mechanism).
2056
2057 **Default:**
2058
2059 If this field is ``NULL``, :c:func:`PyType_Ready` will assign a new
2060 dictionary to it.
2061
2062 .. warning::
2063
2064 It is not safe to use :c:func:`PyDict_SetItem` on or otherwise modify
2065 :c:member:`~PyTypeObject.tp_dict` with the dictionary C-API.
2066
2067
2068 .. c:member:: descrgetfunc PyTypeObject.tp_descr_get
2069
2070 .. corresponding-type-slot:: Py_tp_descr_get
2071
2072 An optional pointer to a "descriptor get" function.
2073
2074 The function signature is::
2075
2076 PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
2077
2078 .. XXX explain more?
2079
2080 **Inheritance:**
2081
2082 This field is inherited by subtypes.
2083
2084
2085 .. c:member:: descrsetfunc PyTypeObject.tp_descr_set
2086
2087 .. corresponding-type-slot:: Py_tp_descr_set
2088
2089 An optional pointer to a function for setting and deleting
2090 a descriptor's value.
2091
2092 The function signature is::
2093
2094 int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
2095
2096 The *value* argument is set to ``NULL`` to delete the value.
2097
2098 .. XXX explain more?
2099
2100 **Inheritance:**
2101
2102 This field is inherited by subtypes.
2103
2104
2105 .. c:member:: Py_ssize_t PyTypeObject.tp_dictoffset
2106
2107 While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_DICT` should be
2108 used instead, if at all possible.
2109
2110 If the instances of this type have a dictionary containing instance variables,
2111 this field is non-zero and contains the offset in the instances of the type of
2112 the instance variable dictionary; this offset is used by
2113 :c:func:`PyObject_GenericGetAttr`.
2114
2115 Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is the dictionary for
2116 attributes of the type object itself.
2117
2118 The value specifies the offset of the dictionary from the start of the instance structure.
2119
2120 The :c:member:`~PyTypeObject.tp_dictoffset` should be regarded as write-only.
2121 To get the pointer to the dictionary call :c:func:`PyObject_GenericGetDict`.
2122 Calling :c:func:`PyObject_GenericGetDict` may need to allocate memory for the
2123 dictionary, so it is may be more efficient to call :c:func:`PyObject_GetAttr`
2124 when accessing an attribute on the object.
2125
2126 It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit and
2127 :c:member:`~PyTypeObject.tp_dictoffset`.
2128
2129 **Inheritance:**
2130
2131 This field is inherited by subtypes. A subtype should not override this offset;
2132 doing so could be unsafe, if C code tries to access the dictionary at the
2133 previous offset.
2134 To properly support inheritance, use :c:macro:`Py_TPFLAGS_MANAGED_DICT`.
2135
2136 **Default:**
2137
2138 This slot has no default. For :ref:`static types <static-types>`, if the
2139 field is ``NULL`` then no :attr:`~object.__dict__` gets created for instances.
2140
2141 If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the
2142 :c:member:`~PyTypeObject.tp_flags` field, then
2143 :c:member:`~PyTypeObject.tp_dictoffset` will be set to ``-1``, to indicate
2144 that it is unsafe to use this field.
2145
2146
2147 .. c:member:: initproc PyTypeObject.tp_init
2148
2149 .. corresponding-type-slot:: Py_tp_init
2150
2151 An optional pointer to an instance initialization function.
2152
2153 This function corresponds to the :meth:`~object.__init__` method of classes. Like
2154 :meth:`!__init__`, it is possible to create an instance without calling
2155 :meth:`!__init__`, and it is possible to reinitialize an instance by calling its
2156 :meth:`!__init__` method again.
2157
2158 The function signature is::
2159
2160 int tp_init(PyObject *self, PyObject *args, PyObject *kwds);
2161
2162 The self argument is the instance to be initialized; the *args* and *kwds*
2163 arguments represent positional and keyword arguments of the call to
2164 :meth:`~object.__init__`.
2165
2166 The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called when an instance is
2167 created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function
2168 has returned an instance of the type. If the :c:member:`~PyTypeObject.tp_new` function returns an
2169 instance of some other type that is not a subtype of the original type, no
2170 :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a
2171 subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called.
2172
2173 Returns ``0`` on success, ``-1`` and sets an exception on error.
2174
2175 **Inheritance:**
2176
2177 This field is inherited by subtypes.
2178
2179 **Default:**
2180
2181 For :ref:`static types <static-types>` this field does not have a default.
2182
2183
2184 .. c:member:: allocfunc PyTypeObject.tp_alloc
2185
2186 .. corresponding-type-slot:: Py_tp_alloc
2187
2188 An optional pointer to an instance allocation function.
2189
2190 The function signature is::
2191
2192 PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
2193
2194 **Inheritance:**
2195
2196 Static subtypes inherit this slot, which will be
2197 :c:func:`PyType_GenericAlloc` if inherited from :class:`object`.
2198
2199 :ref:`Heap subtypes <heap-types>` do not inherit this slot.
2200
2201 **Default:**
2202
2203 For heap subtypes, this field is always set to
2204 :c:func:`PyType_GenericAlloc`.
2205
2206 For static subtypes, this slot is inherited (see above).
2207
2208
2209 .. c:member:: newfunc PyTypeObject.tp_new
2210
2211 .. corresponding-type-slot:: Py_tp_new
2212
2213 An optional pointer to an instance creation function.
2214
2215 The function signature is::
2216
2217 PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
2218
2219 The *subtype* argument is the type of the object being created; the *args* and
2220 *kwds* arguments represent positional and keyword arguments of the call to the
2221 type. Note that *subtype* doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new`
2222 function is called; it may be a subtype of that type (but not an unrelated
2223 type).
2224
2225 The :c:member:`~PyTypeObject.tp_new` function should call ``subtype->tp_alloc(subtype, nitems)``
2226 to allocate space for the object, and then do only as much further
2227 initialization as is absolutely necessary. Initialization that can safely be
2228 ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler. A good
2229 rule of thumb is that for immutable types, all initialization should take place
2230 in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be
2231 deferred to :c:member:`~PyTypeObject.tp_init`.
2232
2233 Set the :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag to disallow creating
2234 instances of the type in Python.
2235
2236 **Inheritance:**
2237
2238 This field is inherited by subtypes, except it is not inherited by
2239 :ref:`static types <static-types>` whose :c:member:`~PyTypeObject.tp_base`
2240 is ``NULL`` or ``&PyBaseObject_Type``.
2241
2242 **Default:**
2243
2244 For :ref:`static types <static-types>` this field has no default.
2245 This means if the slot is defined as ``NULL``, the type cannot be called
2246 to create new instances; presumably there is some other way to create
2247 instances, like a factory function.
2248
2249
2250 .. c:member:: freefunc PyTypeObject.tp_free
2251
2252 .. corresponding-type-slot:: Py_tp_free
2253
2254 An optional pointer to an instance deallocation function. Its signature is::
2255
2256 void tp_free(void *self);
2257
2258 This function must free the memory allocated by
2259 :c:member:`~PyTypeObject.tp_alloc`.
2260
2261 **Inheritance:**
2262
2263 Static subtypes inherit this slot, which will be :c:func:`PyObject_Free` if
2264 inherited from :class:`object`. Exception: If the type supports garbage
2265 collection (i.e., the :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set in
2266 :c:member:`~PyTypeObject.tp_flags`) and it would inherit
2267 :c:func:`PyObject_Free`, then this slot is not inherited but instead defaults
2268 to :c:func:`PyObject_GC_Del`.
2269
2270 :ref:`Heap subtypes <heap-types>` do not inherit this slot.
2271
2272 **Default:**
2273
2274 For :ref:`heap subtypes <heap-types>`, this slot defaults to a deallocator suitable to match
2275 :c:func:`PyType_GenericAlloc` and the value of the
2276 :c:macro:`Py_TPFLAGS_HAVE_GC` flag.
2277
2278 For static subtypes, this slot is inherited (see above).
2279
2280
2281 .. c:member:: inquiry PyTypeObject.tp_is_gc
2282
2283 .. corresponding-type-slot:: Py_tp_is_gc
2284
2285 An optional pointer to a function called by the garbage collector.
2286
2287 The garbage collector needs to know whether a particular object is collectible
2288 or not. Normally, it is sufficient to look at the object's type's
2289 :c:member:`~PyTypeObject.tp_flags` field, and check the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit. But
2290 some types have a mixture of statically and dynamically allocated instances, and
2291 the statically allocated instances are not collectible. Such types should
2292 define this function; it should return ``1`` for a collectible instance, and
2293 ``0`` for a non-collectible instance. The signature is::
2294
2295 int tp_is_gc(PyObject *self);
2296
2297 (The only example of this are types themselves. The metatype,
2298 :c:data:`PyType_Type`, defines this function to distinguish between statically
2299 and :ref:`dynamically allocated types <heap-types>`.)
2300
2301 **Inheritance:**
2302
2303 This field is inherited by subtypes.
2304
2305 **Default:**
2306
2307 This slot has no default. If this field is ``NULL``,
2308 :c:macro:`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent.
2309
2310
2311 .. c:member:: PyObject* PyTypeObject.tp_bases
2312
2313 .. corresponding-type-slot:: Py_tp_bases
2314
2315 Tuple of base types.
2316
2317 This field should be set to ``NULL`` and treated as read-only.
2318 Python will fill it in when the type is :c:func:`initialized <PyType_Ready>`.
2319
2320 For dynamically created classes, the :c:data:`Py_tp_bases`
2321 :c:type:`slot <PyType_Slot>` can be used instead of the *bases* argument
2322 of :c:func:`PyType_FromSpecWithBases`.
2323 The argument form is preferred.
2324
2325 .. warning::
2326
2327 Multiple inheritance does not work well for statically defined types.
2328 If you set ``tp_bases`` to a tuple, Python will not raise an error,
2329 but some slots will only be inherited from the first base.
2330
2331 **Inheritance:**
2332
2333 This field is not inherited.
2334
2335
2336 .. c:member:: PyObject* PyTypeObject.tp_mro
2337
2338 Tuple containing the expanded set of base types, starting with the type itself
2339 and ending with :class:`object`, in Method Resolution Order.
2340
2341 This field should be set to ``NULL`` and treated as read-only.
2342 Python will fill it in when the type is :c:func:`initialized <PyType_Ready>`.
2343
2344 **Inheritance:**
2345
2346 This field is not inherited; it is calculated fresh by
2347 :c:func:`PyType_Ready`.
2348
2349
2350 .. c:member:: PyObject* PyTypeObject.tp_cache
2351
2352 Unused. Internal use only.
2353
2354 **Inheritance:**
2355
2356 This field is not inherited.
2357
2358
2359 .. c:member:: void* PyTypeObject.tp_subclasses
2360
2361 A collection of subclasses. Internal use only. May be an invalid pointer.
2362
2363 To get a list of subclasses, call the Python method
2364 :py:meth:`~type.__subclasses__`.
2365
2366 .. versionchanged:: 3.12
2367
2368 For some types, this field does not hold a valid :c:expr:`PyObject*`.
2369 The type was changed to :c:expr:`void*` to indicate this.
2370
2371 **Inheritance:**
2372
2373 This field is not inherited.
2374
2375
2376 .. c:member:: PyObject* PyTypeObject.tp_weaklist
2377
2378 Weak reference list head, for weak references to this type object. Not
2379 inherited. Internal use only.
2380
2381 .. versionchanged:: 3.12
2382
2383 Internals detail: For the static builtin types this is always ``NULL``,
2384 even if weakrefs are added. Instead, the weakrefs for each are stored
2385 on ``PyInterpreterState``. Use the public C-API or the internal
2386 ``_PyObject_GET_WEAKREFS_LISTPTR()`` macro to avoid the distinction.
2387
2388 **Inheritance:**
2389
2390 This field is not inherited.
2391
2392
2393 .. c:member:: destructor PyTypeObject.tp_del
2394
2395 .. corresponding-type-slot:: Py_tp_del
2396
2397 This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead.
2398
2399
2400 .. c:member:: unsigned int PyTypeObject.tp_version_tag
2401
2402 Used to index into the method cache. Internal use only.
2403
2404 **Inheritance:**
2405
2406 This field is not inherited.
2407
2408
2409 .. c:member:: destructor PyTypeObject.tp_finalize
2410
2411 .. corresponding-type-slot:: Py_tp_finalize
2412
2413 An optional pointer to an instance finalization function. This is the C
2414 implementation of the :meth:`~object.__del__` special method. Its signature
2415 is::
2416
2417 void tp_finalize(PyObject *self);
2418
2419 The primary purpose of finalization is to perform any non-trivial cleanup
2420 that must be performed before the object is destroyed, while the object and
2421 any other objects it directly or indirectly references are still in a
2422 consistent state. The finalizer is allowed to execute
2423 arbitrary Python code.
2424
2425 Before Python automatically finalizes an object, some of the object's direct
2426 or indirect referents might have themselves been automatically finalized.
2427 However, none of the referents will have been automatically cleared
2428 (:c:member:`~PyTypeObject.tp_clear`) yet.
2429
2430 Other non-finalized objects might still be using a finalized object, so the
2431 finalizer must leave the object in a sane state (e.g., invariants are still
2432 met).
2433
2434 .. note::
2435
2436 After Python automatically finalizes an object, Python might start
2437 automatically clearing (:c:member:`~PyTypeObject.tp_clear`) the object
2438 and its referents (direct and indirect). Cleared objects are not
2439 guaranteed to be in a consistent state; a finalized object must be able
2440 to tolerate cleared referents.
2441
2442 .. note::
2443
2444 An object is not guaranteed to be automatically finalized before its
2445 destructor (:c:member:`~PyTypeObject.tp_dealloc`) is called. It is
2446 recommended to call :c:func:`PyObject_CallFinalizerFromDealloc` at the
2447 beginning of :c:member:`!tp_dealloc` to guarantee that the object is
2448 always finalized before destruction.
2449
2450 .. note::
2451
2452 The :c:member:`~PyTypeObject.tp_finalize` function can be called from any
2453 thread, although the :term:`GIL` will be held.
2454
2455 .. note::
2456
2457 The :c:member:`!tp_finalize` function can be called during shutdown,
2458 after some global variables have been deleted. See the documentation of
2459 the :meth:`~object.__del__` method for details.
2460
2461 When Python finalizes an object, it behaves like the following algorithm:
2462
2463 #. Python might mark the object as *finalized*. Currently, Python always
2464 marks objects whose type supports garbage collection (i.e., the
2465 :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set in
2466 :c:member:`~PyTypeObject.tp_flags`) and never marks other types of
2467 objects; this might change in a future version.
2468 #. If the object is not marked as *finalized* and its
2469 :c:member:`!tp_finalize` finalizer function is non-``NULL``, the
2470 finalizer function is called.
2471 #. If the finalizer function was called and the finalizer made the object
2472 reachable (i.e., there is a reference to the object and it is not a
2473 member of a :term:`cyclic isolate`), then the finalizer is said to have
2474 *resurrected* the object. It is unspecified whether the finalizer can
2475 also resurrect the object by adding a new reference to the object that
2476 does not make it reachable, i.e., the object is (still) a member of a
2477 cyclic isolate.
2478 #. If the finalizer resurrected the object, the object's pending destruction
2479 is canceled and the object's *finalized* mark might be removed if
2480 present. Currently, Python never removes the *finalized* mark; this
2481 might change in a future version.
2482
2483 *Automatic finalization* refers to any finalization performed by Python
2484 except via calls to :c:func:`PyObject_CallFinalizer` or
2485 :c:func:`PyObject_CallFinalizerFromDealloc`. No guarantees are made about
2486 when, if, or how often an object is automatically finalized, except:
2487
2488 * Python will not automatically finalize an object if it is reachable, i.e.,
2489 there is a reference to it and it is not a member of a :term:`cyclic
2490 isolate`.
2491 * Python will not automatically finalize an object if finalizing it would
2492 not mark the object as *finalized*. Currently, this applies to objects
2493 whose type does not support garbage collection, i.e., the
2494 :c:macro:`Py_TPFLAGS_HAVE_GC` flag is not set. Such objects can still be
2495 manually finalized by calling :c:func:`PyObject_CallFinalizer` or
2496 :c:func:`PyObject_CallFinalizerFromDealloc`.
2497 * Python will not automatically finalize any two members of a :term:`cyclic
2498 isolate` concurrently.
2499 * Python will not automatically finalize an object after it has
2500 automatically cleared (:c:member:`~PyTypeObject.tp_clear`) the object.
2501 * If an object is a member of a :term:`cyclic isolate`, Python will not
2502 automatically finalize it after automatically clearing (see
2503 :c:member:`~PyTypeObject.tp_clear`) any other member.
2504 * Python will automatically finalize every member of a :term:`cyclic
2505 isolate` before it automatically clears (see
2506 :c:member:`~PyTypeObject.tp_clear`) any of them.
2507 * If Python is going to automatically clear an object
2508 (:c:member:`~PyTypeObject.tp_clear`), it will automatically finalize the
2509 object first.
2510
2511 Python currently only automatically finalizes objects that are members of a
2512 :term:`cyclic isolate`, but future versions might finalize objects regularly
2513 before their destruction.
2514
2515 To manually finalize an object, do not call this function directly; call
2516 :c:func:`PyObject_CallFinalizer` or
2517 :c:func:`PyObject_CallFinalizerFromDealloc` instead.
2518
2519 :c:member:`~PyTypeObject.tp_finalize` should leave the current exception
2520 status unchanged. The recommended way to write a non-trivial finalizer is
2521 to back up the exception at the beginning by calling
2522 :c:func:`PyErr_GetRaisedException` and restore the exception at the end by
2523 calling :c:func:`PyErr_SetRaisedException`. If an exception is encountered
2524 in the middle of the finalizer, log and clear it with
2525 :c:func:`PyErr_WriteUnraisable` or :c:func:`PyErr_FormatUnraisable`. For
2526 example::
2527
2528 static void
2529 foo_finalize(PyObject *self)
2530 {
2531 // Save the current exception, if any.
2532 PyObject *exc = PyErr_GetRaisedException();
2533
2534 // ...
2535
2536 if (do_something_that_might_raise() != success_indicator) {
2537 PyErr_WriteUnraisable(self);
2538 goto done;
2539 }
2540
2541 done:
2542 // Restore the saved exception. This silently discards any exception
2543 // raised above, so be sure to call PyErr_WriteUnraisable first if
2544 // necessary.
2545 PyErr_SetRaisedException(exc);
2546 }
2547
2548 **Inheritance:**
2549
2550 This field is inherited by subtypes.
2551
2552 .. versionadded:: 3.4
2553
2554 .. versionchanged:: 3.8
2555
2556 Before version 3.8 it was necessary to set the
2557 :c:macro:`Py_TPFLAGS_HAVE_FINALIZE` flags bit in order for this field to be
2558 used. This is no longer required.
2559
2560 .. seealso::
2561
2562 * :pep:`442`: "Safe object finalization"
2563 * :ref:`life-cycle` for details about how this slot relates to other
2564 slots.
2565 * :c:func:`PyObject_CallFinalizer`
2566 * :c:func:`PyObject_CallFinalizerFromDealloc`
2567
2568
2569 .. c:member:: vectorcallfunc PyTypeObject.tp_vectorcall
2570
2571 .. corresponding-type-slot:: Py_tp_vectorcall
2572
2573 A :ref:`vectorcall function <vectorcall>` to use for calls of this type
2574 object (rather than instances).
2575 In other words, ``tp_vectorcall`` can be used to optimize ``type.__call__``,
2576 which typically returns a new instance of *type*.
2577
2578 As with any vectorcall function, if ``tp_vectorcall`` is ``NULL``,
2579 the *tp_call* protocol (``Py_TYPE(type)->tp_call``) is used instead.
2580
2581 .. note::
2582
2583 The :ref:`vectorcall protocol <vectorcall>` requires that the vectorcall
2584 function has the same behavior as the corresponding ``tp_call``.
2585 This means that ``type->tp_vectorcall`` must match the behavior of
2586 ``Py_TYPE(type)->tp_call``.
2587
2588 Specifically, if *type* uses the default metaclass,
2589 ``type->tp_vectorcall`` must behave the same as
2590 :c:expr:`PyType_Type->tp_call`, which:
2591
2592 - calls ``type->tp_new``,
2593
2594 - if the result is a subclass of *type*, calls ``type->tp_init``
2595 on the result of ``tp_new``, and
2596
2597 - returns the result of ``tp_new``.
2598
2599 Typically, ``tp_vectorcall`` is overridden to optimize this process
2600 for specific :c:member:`~PyTypeObject.tp_new` and
2601 :c:member:`~PyTypeObject.tp_init`.
2602 When doing this for user-subclassable types, note that both can be
2603 overridden (using :py:func:`~object.__new__` and
2604 :py:func:`~object.__init__`, respectively).
2605
2606
2607
2608 **Inheritance:**
2609
2610 This field is never inherited.
2611
2612 .. versionadded:: 3.9 (the field exists since 3.8 but it's only used since 3.9)
2613
2614
2615 .. c:member:: unsigned char PyTypeObject.tp_watched
2616
2617 Internal. Do not use.
2618
2619 .. versionadded:: 3.12
2620
2621
2622 .. _static-types:
2623
2624 Static Types
2625 ------------
2626
2627 Traditionally, types defined in C code are *static*, that is,
2628 a static :c:type:`PyTypeObject` structure is defined directly in code
2629 and initialized using :c:func:`PyType_Ready`.
2630
2631 This results in types that are limited relative to types defined in Python:
2632
2633 * Static types are limited to one base, i.e. they cannot use multiple
2634 inheritance.
2635 * Static type objects (but not necessarily their instances) are immutable.
2636 It is not possible to add or modify the type object's attributes from Python.
2637 * Static type objects are shared across
2638 :ref:`sub-interpreters <sub-interpreter-support>`, so they should not
2639 include any subinterpreter-specific state.
2640
2641 Also, since :c:type:`PyTypeObject` is only part of the :ref:`Limited API
2642 <limited-c-api>` as an opaque struct, any extension modules using static types must be
2643 compiled for a specific Python minor version.
2644
2645
2646 .. _heap-types:
2647
2648 Heap Types
2649 ----------
2650
2651 An alternative to :ref:`static types <static-types>` is *heap-allocated types*,
2652 or *heap types* for short, which correspond closely to classes created by
2653 Python's ``class`` statement. Heap types have the :c:macro:`Py_TPFLAGS_HEAPTYPE`
2654 flag set.
2655
2656 This is done by filling a :c:type:`PyType_Spec` structure and calling
2657 :c:func:`PyType_FromSpec`, :c:func:`PyType_FromSpecWithBases`,
2658 :c:func:`PyType_FromModuleAndSpec`, or :c:func:`PyType_FromMetaclass`.
2659
2660
2661 .. _number-structs:
2662
2663 Number Object Structures
2664 ------------------------
2665
2666 .. sectionauthor:: Amaury Forgeot d'Arc
2667
2668
2669 .. c:type:: PyNumberMethods
2670
2671 This structure holds pointers to the functions which an object uses to
2672 implement the number protocol. Each function is used by the function of
2673 similar name documented in the :ref:`number` section.
2674
2675 .. XXX Drop the definition?
2676
2677 Here is the structure definition::
2678
2679 typedef struct {
2680 binaryfunc nb_add;
2681 binaryfunc nb_subtract;
2682 binaryfunc nb_multiply;
2683 binaryfunc nb_remainder;
2684 binaryfunc nb_divmod;
2685 ternaryfunc nb_power;
2686 unaryfunc nb_negative;
2687 unaryfunc nb_positive;
2688 unaryfunc nb_absolute;
2689 inquiry nb_bool;
2690 unaryfunc nb_invert;
2691 binaryfunc nb_lshift;
2692 binaryfunc nb_rshift;
2693 binaryfunc nb_and;
2694 binaryfunc nb_xor;
2695 binaryfunc nb_or;
2696 unaryfunc nb_int;
2697 void *nb_reserved;
2698 unaryfunc nb_float;
2699
2700 binaryfunc nb_inplace_add;
2701 binaryfunc nb_inplace_subtract;
2702 binaryfunc nb_inplace_multiply;
2703 binaryfunc nb_inplace_remainder;
2704 ternaryfunc nb_inplace_power;
2705 binaryfunc nb_inplace_lshift;
2706 binaryfunc nb_inplace_rshift;
2707 binaryfunc nb_inplace_and;
2708 binaryfunc nb_inplace_xor;
2709 binaryfunc nb_inplace_or;
2710
2711 binaryfunc nb_floor_divide;
2712 binaryfunc nb_true_divide;
2713 binaryfunc nb_inplace_floor_divide;
2714 binaryfunc nb_inplace_true_divide;
2715
2716 unaryfunc nb_index;
2717
2718 binaryfunc nb_matrix_multiply;
2719 binaryfunc nb_inplace_matrix_multiply;
2720 } PyNumberMethods;
2721
2722 .. note::
2723
2724 Binary and ternary functions must check the type of all their operands,
2725 and implement the necessary conversions (at least one of the operands is
2726 an instance of the defined type). If the operation is not defined for the
2727 given operands, binary and ternary functions must return
2728 ``Py_NotImplemented``, if another error occurred they must return ``NULL``
2729 and set an exception.
2730
2731 .. note::
2732
2733 The :c:member:`~PyNumberMethods.nb_reserved` field should always be ``NULL``. It
2734 was previously called :c:member:`!nb_long`, and was renamed in
2735 Python 3.0.1.
2736
2737 .. c:member:: binaryfunc PyNumberMethods.nb_add
2738
2739 .. corresponding-type-slot:: Py_nb_add
2740
2741 .. c:member:: binaryfunc PyNumberMethods.nb_subtract
2742
2743 .. corresponding-type-slot:: Py_nb_subtract
2744
2745 .. c:member:: binaryfunc PyNumberMethods.nb_multiply
2746
2747 .. corresponding-type-slot:: Py_nb_multiply
2748
2749 .. c:member:: binaryfunc PyNumberMethods.nb_remainder
2750
2751 .. corresponding-type-slot:: Py_nb_remainder
2752
2753 .. c:member:: binaryfunc PyNumberMethods.nb_divmod
2754
2755 .. corresponding-type-slot:: Py_nb_divmod
2756
2757 .. c:member:: ternaryfunc PyNumberMethods.nb_power
2758
2759 .. corresponding-type-slot:: Py_nb_power
2760
2761 .. c:member:: unaryfunc PyNumberMethods.nb_negative
2762
2763 .. corresponding-type-slot:: Py_nb_negative
2764
2765 .. c:member:: unaryfunc PyNumberMethods.nb_positive
2766
2767 .. corresponding-type-slot:: Py_nb_positive
2768
2769 .. c:member:: unaryfunc PyNumberMethods.nb_absolute
2770
2771 .. corresponding-type-slot:: Py_nb_absolute
2772
2773 .. c:member:: inquiry PyNumberMethods.nb_bool
2774
2775 .. corresponding-type-slot:: Py_nb_bool
2776
2777 .. c:member:: unaryfunc PyNumberMethods.nb_invert
2778
2779 .. corresponding-type-slot:: Py_nb_invert
2780
2781 .. c:member:: binaryfunc PyNumberMethods.nb_lshift
2782
2783 .. corresponding-type-slot:: Py_nb_lshift
2784
2785 .. c:member:: binaryfunc PyNumberMethods.nb_rshift
2786
2787 .. corresponding-type-slot:: Py_nb_rshift
2788
2789 .. c:member:: binaryfunc PyNumberMethods.nb_and
2790
2791 .. corresponding-type-slot:: Py_nb_and
2792
2793 .. c:member:: binaryfunc PyNumberMethods.nb_xor
2794
2795 .. corresponding-type-slot:: Py_nb_xor
2796
2797 .. c:member:: binaryfunc PyNumberMethods.nb_or
2798
2799 .. corresponding-type-slot:: Py_nb_or
2800
2801 .. c:member:: unaryfunc PyNumberMethods.nb_int
2802
2803 .. corresponding-type-slot:: Py_nb_int
2804
2805 .. c:member:: void *PyNumberMethods.nb_reserved
2806
2807 .. c:member:: unaryfunc PyNumberMethods.nb_float
2808
2809 .. corresponding-type-slot:: Py_nb_float
2810
2811 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_add
2812
2813 .. corresponding-type-slot:: Py_nb_inplace_add
2814
2815 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_subtract
2816
2817 .. corresponding-type-slot:: Py_nb_inplace_subtract
2818
2819 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_multiply
2820
2821 .. corresponding-type-slot:: Py_nb_inplace_multiply
2822
2823 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_remainder
2824
2825 .. corresponding-type-slot:: Py_nb_inplace_remainder
2826
2827 .. c:member:: ternaryfunc PyNumberMethods.nb_inplace_power
2828
2829 .. corresponding-type-slot:: Py_nb_inplace_power
2830
2831 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_lshift
2832
2833 .. corresponding-type-slot:: Py_nb_inplace_lshift
2834
2835 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_rshift
2836
2837 .. corresponding-type-slot:: Py_nb_inplace_rshift
2838
2839 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_and
2840
2841 .. corresponding-type-slot:: Py_nb_inplace_and
2842
2843 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_xor
2844
2845 .. corresponding-type-slot:: Py_nb_inplace_xor
2846
2847 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_or
2848
2849 .. corresponding-type-slot:: Py_nb_inplace_or
2850
2851 .. c:member:: binaryfunc PyNumberMethods.nb_floor_divide
2852
2853 .. corresponding-type-slot:: Py_nb_floor_divide
2854
2855 .. c:member:: binaryfunc PyNumberMethods.nb_true_divide
2856
2857 .. corresponding-type-slot:: Py_nb_true_divide
2858
2859 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_floor_divide
2860
2861 .. corresponding-type-slot:: Py_nb_inplace_floor_divide
2862
2863 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_true_divide
2864
2865 .. corresponding-type-slot:: Py_nb_inplace_true_divide
2866
2867 .. c:member:: unaryfunc PyNumberMethods.nb_index
2868
2869 .. corresponding-type-slot:: Py_nb_index
2870
2871 .. c:member:: binaryfunc PyNumberMethods.nb_matrix_multiply
2872
2873 .. corresponding-type-slot:: Py_nb_matrix_multiply
2874
2875 .. c:member:: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
2876
2877 .. corresponding-type-slot:: Py_nb_inplace_matrix_multiply
2878
2879
2880
2881 .. _mapping-structs:
2882
2883 Mapping Object Structures
2884 -------------------------
2885
2886 .. sectionauthor:: Amaury Forgeot d'Arc
2887
2888
2889 .. c:type:: PyMappingMethods
2890
2891 This structure holds pointers to the functions which an object uses to
2892 implement the mapping protocol. It has three members:
2893
2894 .. c:member:: lenfunc PyMappingMethods.mp_length
2895
2896 .. corresponding-type-slot:: Py_mp_length
2897
2898 This function is used by :c:func:`PyMapping_Size` and
2899 :c:func:`PyObject_Size`, and has the same signature. This slot may be set to
2900 ``NULL`` if the object has no defined length.
2901
2902 .. c:member:: binaryfunc PyMappingMethods.mp_subscript
2903
2904 .. corresponding-type-slot:: Py_mp_subscript
2905
2906 This function is used by :c:func:`PyObject_GetItem` and
2907 :c:func:`PySequence_GetSlice`, and has the same signature as
2908 :c:func:`!PyObject_GetItem`. This slot must be filled for the
2909 :c:func:`PyMapping_Check` function to return ``1``, it can be ``NULL``
2910 otherwise.
2911
2912 .. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript
2913
2914 .. corresponding-type-slot:: Py_mp_ass_subscript
2915
2916 This function is used by :c:func:`PyObject_SetItem`,
2917 :c:func:`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and
2918 :c:func:`PySequence_DelSlice`. It has the same signature as
2919 :c:func:`!PyObject_SetItem`, but *v* can also be set to ``NULL`` to delete
2920 an item. If this slot is ``NULL``, the object does not support item
2921 assignment and deletion.
2922
2923
2924 .. _sequence-structs:
2925
2926 Sequence Object Structures
2927 --------------------------
2928
2929 .. sectionauthor:: Amaury Forgeot d'Arc
2930
2931
2932 .. c:type:: PySequenceMethods
2933
2934 This structure holds pointers to the functions which an object uses to
2935 implement the sequence protocol.
2936
2937 .. c:member:: lenfunc PySequenceMethods.sq_length
2938
2939 .. corresponding-type-slot:: Py_sq_length
2940
2941 This function is used by :c:func:`PySequence_Size` and
2942 :c:func:`PyObject_Size`, and has the same signature. It is also used for
2943 handling negative indices via the :c:member:`~PySequenceMethods.sq_item`
2944 and the :c:member:`~PySequenceMethods.sq_ass_item` slots.
2945
2946 .. c:member:: binaryfunc PySequenceMethods.sq_concat
2947
2948 .. corresponding-type-slot:: Py_sq_concat
2949
2950 This function is used by :c:func:`PySequence_Concat` and has the same
2951 signature. It is also used by the ``+`` operator, after trying the numeric
2952 addition via the :c:member:`~PyNumberMethods.nb_add` slot.
2953
2954 .. c:member:: ssizeargfunc PySequenceMethods.sq_repeat
2955
2956 .. corresponding-type-slot:: Py_sq_repeat
2957
2958 This function is used by :c:func:`PySequence_Repeat` and has the same
2959 signature. It is also used by the ``*`` operator, after trying numeric
2960 multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot.
2961
2962 .. c:member:: ssizeargfunc PySequenceMethods.sq_item
2963
2964 .. corresponding-type-slot:: Py_sq_item
2965
2966 This function is used by :c:func:`PySequence_GetItem` and has the same
2967 signature. It is also used by :c:func:`PyObject_GetItem`, after trying
2968 the subscription via the :c:member:`~PyMappingMethods.mp_subscript` slot.
2969 This slot must be filled for the :c:func:`PySequence_Check`
2970 function to return ``1``, it can be ``NULL`` otherwise.
2971
2972 Negative indexes are handled as follows: if the :c:member:`~PySequenceMethods.sq_length` slot is
2973 filled, it is called and the sequence length is used to compute a positive
2974 index which is passed to :c:member:`~PySequenceMethods.sq_item`. If :c:member:`!sq_length` is ``NULL``,
2975 the index is passed as is to the function.
2976
2977 .. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item
2978
2979 .. corresponding-type-slot:: Py_sq_ass_item
2980
2981 This function is used by :c:func:`PySequence_SetItem` and has the same
2982 signature. It is also used by :c:func:`PyObject_SetItem` and
2983 :c:func:`PyObject_DelItem`, after trying the item assignment and deletion
2984 via the :c:member:`~PyMappingMethods.mp_ass_subscript` slot.
2985 This slot may be left to ``NULL`` if the object does not support
2986 item assignment and deletion.
2987
2988 .. c:member:: objobjproc PySequenceMethods.sq_contains
2989
2990 .. corresponding-type-slot:: Py_sq_contains
2991
2992 This function may be used by :c:func:`PySequence_Contains` and has the same
2993 signature. This slot may be left to ``NULL``, in this case
2994 :c:func:`!PySequence_Contains` simply traverses the sequence until it
2995 finds a match.
2996
2997 .. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat
2998
2999 .. corresponding-type-slot:: Py_sq_inplace_concat
3000
3001 This function is used by :c:func:`PySequence_InPlaceConcat` and has the same
3002 signature. It should modify its first operand, and return it. This slot
3003 may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceConcat`
3004 will fall back to :c:func:`PySequence_Concat`. It is also used by the
3005 augmented assignment ``+=``, after trying numeric in-place addition
3006 via the :c:member:`~PyNumberMethods.nb_inplace_add` slot.
3007
3008 .. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat
3009
3010 .. corresponding-type-slot:: Py_sq_inplace_repeat
3011
3012 This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same
3013 signature. It should modify its first operand, and return it. This slot
3014 may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceRepeat`
3015 will fall back to :c:func:`PySequence_Repeat`. It is also used by the
3016 augmented assignment ``*=``, after trying numeric in-place multiplication
3017 via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot.
3018
3019
3020 .. _buffer-structs:
3021
3022 Buffer Object Structures
3023 ------------------------
3024
3025 .. sectionauthor:: Greg J. Stein <[email protected]>
3026 .. sectionauthor:: Benjamin Peterson
3027 .. sectionauthor:: Stefan Krah
3028
3029 .. c:type:: PyBufferProcs
3030
3031 This structure holds pointers to the functions required by the
3032 :ref:`Buffer protocol <bufferobjects>`. The protocol defines how
3033 an exporter object can expose its internal data to consumer objects.
3034
3035 .. c:member:: getbufferproc PyBufferProcs.bf_getbuffer
3036
3037 .. corresponding-type-slot:: Py_bf_getbuffer
3038
3039 The signature of this function is::
3040
3041 int (PyObject *exporter, Py_buffer *view, int flags);
3042
3043 Handle a request to *exporter* to fill in *view* as specified by *flags*.
3044 Except for point (3), an implementation of this function MUST take these
3045 steps:
3046
3047 (1) Check if the request can be met. If not, raise :exc:`BufferError`,
3048 set ``view->obj`` to ``NULL`` and return ``-1``.
3049
3050 (2) Fill in the requested fields.
3051
3052 (3) Increment an internal counter for the number of exports.
3053
3054 (4) Set ``view->obj`` to *exporter* and increment ``view->obj``.
3055
3056 (5) Return ``0``.
3057
3058 **Thread safety:**
3059
3060 In the :term:`free-threaded build`, implementations must ensure:
3061
3062 * The export counter increment in step (3) is atomic.
3063
3064 * The underlying buffer data remains valid and at a stable memory
3065 location for the lifetime of all exports.
3066
3067 * For objects that support resizing or reallocation (such as
3068 :class:`bytearray`), the export counter is checked atomically before
3069 such operations, and :exc:`BufferError` is raised if exports exist.
3070
3071 * The function is safe to call concurrently from multiple threads.
3072
3073 See also :ref:`thread-safety-memoryview` for the Python-level
3074 thread safety guarantees of :class:`memoryview` objects.
3075
3076 If *exporter* is part of a chain or tree of buffer providers, two main
3077 schemes can be used:
3078
3079 * Re-export: Each member of the tree acts as the exporting object and
3080 sets ``view->obj`` to a new reference to itself.
3081
3082 * Redirect: The buffer request is redirected to the root object of the
3083 tree. Here, ``view->obj`` will be a new reference to the root
3084 object.
3085
3086 The individual fields of *view* are described in section
3087 :ref:`Buffer structure <buffer-structure>`, the rules how an exporter
3088 must react to specific requests are in section
3089 :ref:`Buffer request types <buffer-request-types>`.
3090
3091 All memory pointed to in the :c:type:`Py_buffer` structure belongs to
3092 the exporter and must remain valid until there are no consumers left.
3093 :c:member:`~Py_buffer.format`, :c:member:`~Py_buffer.shape`,
3094 :c:member:`~Py_buffer.strides`, :c:member:`~Py_buffer.suboffsets`
3095 and :c:member:`~Py_buffer.internal`
3096 are read-only for the consumer.
3097
3098 :c:func:`PyBuffer_FillInfo` provides an easy way of exposing a simple
3099 bytes buffer while dealing correctly with all request types.
3100
3101 :c:func:`PyObject_GetBuffer` is the interface for the consumer that
3102 wraps this function.
3103
3104 .. c:member:: releasebufferproc PyBufferProcs.bf_releasebuffer
3105
3106 .. corresponding-type-slot:: Py_bf_releasebuffer
3107
3108 The signature of this function is::
3109
3110 void (PyObject *exporter, Py_buffer *view);
3111
3112 Handle a request to release the resources of the buffer. If no resources
3113 need to be released, :c:member:`PyBufferProcs.bf_releasebuffer` may be
3114 ``NULL``. Otherwise, a standard implementation of this function will take
3115 these optional steps:
3116
3117 (1) Decrement an internal counter for the number of exports.
3118
3119 (2) If the counter is ``0``, free all memory associated with *view*.
3120
3121 **Thread safety:**
3122
3123 In the :term:`free-threaded build`:
3124
3125 * The export counter decrement in step (1) must be atomic.
3126
3127 * Resource cleanup when the counter reaches zero must be done atomically,
3128 as the final release may race with concurrent releases from other
3129 threads and dellocation must only happen once.
3130
3131 The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep
3132 track of buffer-specific resources. This field is guaranteed to remain
3133 constant, while a consumer MAY pass a copy of the original buffer as the
3134 *view* argument.
3135
3136
3137 This function MUST NOT decrement ``view->obj``, since that is
3138 done automatically in :c:func:`PyBuffer_Release` (this scheme is
3139 useful for breaking reference cycles).
3140
3141
3142 :c:func:`PyBuffer_Release` is the interface for the consumer that
3143 wraps this function.
3144
3145
3146 .. _async-structs:
3147
3148
3149 Async Object Structures
3150 -----------------------
3151
3152 .. sectionauthor:: Yury Selivanov <[email protected]>
3153
3154 .. versionadded:: 3.5
3155
3156 .. c:type:: PyAsyncMethods
3157
3158 This structure holds pointers to the functions required to implement
3159 :term:`awaitable` and :term:`asynchronous iterator` objects.
3160
3161 Here is the structure definition::
3162
3163 typedef struct {
3164 unaryfunc am_await;
3165 unaryfunc am_aiter;
3166 unaryfunc am_anext;
3167 sendfunc am_send;
3168 } PyAsyncMethods;
3169
3170 .. c:member:: unaryfunc PyAsyncMethods.am_await
3171
3172 .. corresponding-type-slot:: Py_am_await
3173
3174 The signature of this function is::
3175
3176 PyObject *am_await(PyObject *self);
3177
3178 The returned object must be an :term:`iterator`, i.e. :c:func:`PyIter_Check`
3179 must return ``1`` for it.
3180
3181 This slot may be set to ``NULL`` if an object is not an :term:`awaitable`.
3182
3183 .. c:member:: unaryfunc PyAsyncMethods.am_aiter
3184
3185 .. corresponding-type-slot:: Py_am_aiter
3186
3187 The signature of this function is::
3188
3189 PyObject *am_aiter(PyObject *self);
3190
3191 Must return an :term:`asynchronous iterator` object.
3192 See :meth:`~object.__anext__` for details.
3193
3194 This slot may be set to ``NULL`` if an object does not implement
3195 asynchronous iteration protocol.
3196
3197 .. c:member:: unaryfunc PyAsyncMethods.am_anext
3198
3199 .. corresponding-type-slot:: Py_am_anext
3200
3201 The signature of this function is::
3202
3203 PyObject *am_anext(PyObject *self);
3204
3205 Must return an :term:`awaitable` object.
3206 See :meth:`~object.__anext__` for details.
3207 This slot may be set to ``NULL``.
3208
3209 .. c:member:: sendfunc PyAsyncMethods.am_send
3210
3211 .. corresponding-type-slot:: Py_am_send
3212
3213 The signature of this function is::
3214
3215 PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
3216
3217 See :c:func:`PyIter_Send` for details.
3218 This slot may be set to ``NULL``.
3219
3220 .. versionadded:: 3.10
3221
3222
3223 .. _slot-typedefs:
3224
3225 Slot Type typedefs
3226 ------------------
3227
3228 .. c:type:: PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
3229
3230 The purpose of this function is to separate memory allocation from memory
3231 initialization. It should return a pointer to a block of memory of adequate
3232 length for the instance, suitably aligned, and initialized to zeros, but with
3233 :c:member:`~PyObject.ob_refcnt` set to ``1`` and :c:member:`~PyObject.ob_type` set to the type argument. If
3234 the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :c:member:`~PyVarObject.ob_size` field
3235 should be initialized to *nitems* and the length of the allocated memory block
3236 should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of
3237 ``sizeof(void*)``; otherwise, *nitems* is not used and the length of the block
3238 should be :c:member:`~PyTypeObject.tp_basicsize`.
3239
3240 This function should not do any other instance initialization, not even to
3241 allocate additional memory; that should be done by :c:member:`~PyTypeObject.tp_new`.
3242
3243 .. c:type:: void (*destructor)(PyObject *)
3244
3245 .. c:type:: void (*freefunc)(void *)
3246
3247 See :c:member:`~PyTypeObject.tp_free`.
3248
3249 .. c:type:: PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *)
3250
3251 See :c:member:`~PyTypeObject.tp_new`.
3252
3253 .. c:type:: int (*initproc)(PyObject *, PyObject *, PyObject *)
3254
3255 See :c:member:`~PyTypeObject.tp_init`.
3256
3257 .. c:type:: PyObject *(*reprfunc)(PyObject *)
3258
3259 See :c:member:`~PyTypeObject.tp_repr`.
3260
3261 .. c:type:: PyObject *(*getattrfunc)(PyObject *self, char *attr)
3262
3263 Return the value of the named attribute for the object.
3264
3265 .. c:type:: int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
3266
3267 Set the value of the named attribute for the object.
3268 The value argument is set to ``NULL`` to delete the attribute.
3269
3270 .. c:type:: PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
3271
3272 Return the value of the named attribute for the object.
3273
3274 See :c:member:`~PyTypeObject.tp_getattro`.
3275
3276 .. c:type:: int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
3277
3278 Set the value of the named attribute for the object.
3279 The value argument is set to ``NULL`` to delete the attribute.
3280
3281 See :c:member:`~PyTypeObject.tp_setattro`.
3282
3283 .. c:type:: PyObject *(*descrgetfunc)(PyObject *, PyObject *, PyObject *)
3284
3285 See :c:member:`~PyTypeObject.tp_descr_get`.
3286
3287 .. c:type:: int (*descrsetfunc)(PyObject *, PyObject *, PyObject *)
3288
3289 See :c:member:`~PyTypeObject.tp_descr_set`.
3290
3291 .. c:type:: Py_hash_t (*hashfunc)(PyObject *)
3292
3293 See :c:member:`~PyTypeObject.tp_hash`.
3294
3295 .. c:type:: PyObject *(*richcmpfunc)(PyObject *, PyObject *, int)
3296
3297 See :c:member:`~PyTypeObject.tp_richcompare`.
3298
3299 .. c:type:: PyObject *(*getiterfunc)(PyObject *)
3300
3301 See :c:member:`~PyTypeObject.tp_iter`.
3302
3303 .. c:type:: PyObject *(*iternextfunc)(PyObject *)
3304
3305 See :c:member:`~PyTypeObject.tp_iternext`.
3306
3307 .. c:type:: Py_ssize_t (*lenfunc)(PyObject *)
3308
3309 .. c:type:: int (*getbufferproc)(PyObject *, Py_buffer *, int)
3310
3311 .. c:type:: void (*releasebufferproc)(PyObject *, Py_buffer *)
3312
3313 .. c:type:: PyObject *(*unaryfunc)(PyObject *)
3314
3315 .. c:type:: PyObject *(*binaryfunc)(PyObject *, PyObject *)
3316
3317 .. c:type:: PySendResult (*sendfunc)(PyObject *, PyObject *, PyObject **)
3318
3319 See :c:member:`~PyAsyncMethods.am_send`.
3320
3321 .. c:type:: PyObject *(*ternaryfunc)(PyObject *, PyObject *, PyObject *)
3322
3323 .. c:type:: PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t)
3324
3325 .. c:type:: int (*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *)
3326
3327 .. c:type:: int (*objobjproc)(PyObject *, PyObject *)
3328
3329 .. c:type:: int (*objobjargproc)(PyObject *, PyObject *, PyObject *)
3330
3331
3332 .. _typedef-examples:
3333
3334 Examples
3335 --------
3336
3337 The following are simple examples of Python type definitions. They
3338 include common usage you may encounter. Some demonstrate tricky corner
3339 cases. For more examples, practical info, and a tutorial, see
3340 :ref:`defining-new-types` and :ref:`new-types-topics`.
3341
3342 A basic :ref:`static type <static-types>`::
3343
3344 typedef struct {
3345 PyObject_HEAD
3346 const char *data;
3347 } MyObject;
3348
3349 static PyTypeObject MyObject_Type = {
3350 PyVarObject_HEAD_INIT(NULL, 0)
3351 .tp_name = "mymod.MyObject",
3352 .tp_basicsize = sizeof(MyObject),
3353 .tp_doc = PyDoc_STR("My objects"),
3354 .tp_new = myobj_new,
3355 .tp_dealloc = (destructor)myobj_dealloc,
3356 .tp_repr = (reprfunc)myobj_repr,
3357 };
3358
3359 You may also find older code (especially in the CPython code base)
3360 with a more verbose initializer::
3361
3362 static PyTypeObject MyObject_Type = {
3363 PyVarObject_HEAD_INIT(NULL, 0)
3364 "mymod.MyObject", /* tp_name */
3365 sizeof(MyObject), /* tp_basicsize */
3366 0, /* tp_itemsize */
3367 (destructor)myobj_dealloc, /* tp_dealloc */
3368 0, /* tp_vectorcall_offset */
3369 0, /* tp_getattr */
3370 0, /* tp_setattr */
3371 0, /* tp_as_async */
3372 (reprfunc)myobj_repr, /* tp_repr */
3373 0, /* tp_as_number */
3374 0, /* tp_as_sequence */
3375 0, /* tp_as_mapping */
3376 0, /* tp_hash */
3377 0, /* tp_call */
3378 0, /* tp_str */
3379 0, /* tp_getattro */
3380 0, /* tp_setattro */
3381 0, /* tp_as_buffer */
3382 0, /* tp_flags */
3383 PyDoc_STR("My objects"), /* tp_doc */
3384 0, /* tp_traverse */
3385 0, /* tp_clear */
3386 0, /* tp_richcompare */
3387 0, /* tp_weaklistoffset */
3388 0, /* tp_iter */
3389 0, /* tp_iternext */
3390 0, /* tp_methods */
3391 0, /* tp_members */
3392 0, /* tp_getset */
3393 0, /* tp_base */
3394 0, /* tp_dict */
3395 0, /* tp_descr_get */
3396 0, /* tp_descr_set */
3397 0, /* tp_dictoffset */
3398 0, /* tp_init */
3399 0, /* tp_alloc */
3400 myobj_new, /* tp_new */
3401 };
3402
3403 A type that supports weakrefs, instance dicts, and hashing::
3404
3405 typedef struct {
3406 PyObject_HEAD
3407 const char *data;
3408 } MyObject;
3409
3410 static PyTypeObject MyObject_Type = {
3411 PyVarObject_HEAD_INIT(NULL, 0)
3412 .tp_name = "mymod.MyObject",
3413 .tp_basicsize = sizeof(MyObject),
3414 .tp_doc = PyDoc_STR("My objects"),
3415 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3416 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
3417 Py_TPFLAGS_MANAGED_WEAKREF,
3418 .tp_new = myobj_new,
3419 .tp_traverse = (traverseproc)myobj_traverse,
3420 .tp_clear = (inquiry)myobj_clear,
3421 .tp_alloc = PyType_GenericNew,
3422 .tp_dealloc = (destructor)myobj_dealloc,
3423 .tp_repr = (reprfunc)myobj_repr,
3424 .tp_hash = (hashfunc)myobj_hash,
3425 .tp_richcompare = PyBaseObject_Type.tp_richcompare,
3426 };
3427
3428 A str subclass that cannot be subclassed and cannot be called
3429 to create instances (e.g. uses a separate factory func) using
3430 :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag::
3431
3432 typedef struct {
3433 PyUnicodeObject raw;
3434 char *extra;
3435 } MyStr;
3436
3437 static PyTypeObject MyStr_Type = {
3438 PyVarObject_HEAD_INIT(NULL, 0)
3439 .tp_name = "mymod.MyStr",
3440 .tp_basicsize = sizeof(MyStr),
3441 .tp_base = NULL, // set to &PyUnicode_Type in module init
3442 .tp_doc = PyDoc_STR("my custom str"),
3443 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
3444 .tp_repr = (reprfunc)myobj_repr,
3445 };
3446
3447 The simplest :ref:`static type <static-types>` with fixed-length instances::
3448
3449 typedef struct {
3450 PyObject_HEAD
3451 } MyObject;
3452
3453 static PyTypeObject MyObject_Type = {
3454 PyVarObject_HEAD_INIT(NULL, 0)
3455 .tp_name = "mymod.MyObject",
3456 };
3457
3458 The simplest :ref:`static type <static-types>` with variable-length instances::
3459
3460 typedef struct {
3461 PyObject_VAR_HEAD
3462 const char *data[1];
3463 } MyObject;
3464
3465 static PyTypeObject MyObject_Type = {
3466 PyVarObject_HEAD_INIT(NULL, 0)
3467 .tp_name = "mymod.MyObject",
3468 .tp_basicsize = sizeof(MyObject) - sizeof(char *),
3469 .tp_itemsize = sizeof(char *),
3470 };