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