Debian Codegraph @

Doc/c-api/type.rst

raw
1 .. highlight:: c
2
3 .. _typeobjects:
4
5 Type Objects
6 ------------
7
8 .. index:: pair: object; type
9
10
11 .. c:type:: PyTypeObject
12
13 The C structure of the objects used to describe built-in types.
14
15
16 .. c:var:: PyTypeObject PyType_Type
17
18 This is the type object for type objects; it is the same object as
19 :class:`type` in the Python layer.
20
21
22 .. c:function:: int PyType_Check(PyObject *o)
23
24 Return non-zero if the object *o* is a type object, including instances of
25 types derived from the standard type object. Return 0 in all other cases.
26 This function always succeeds.
27
28
29 .. c:function:: int PyType_CheckExact(PyObject *o)
30
31 Return non-zero if the object *o* is a type object, but not a subtype of
32 the standard type object. Return 0 in all other cases. This function
33 always succeeds.
34
35
36 .. c:function:: unsigned int PyType_ClearCache()
37
38 Clear the internal lookup cache. Return the current version tag.
39
40 .. c:function:: unsigned long PyType_GetFlags(PyTypeObject* type)
41
42 Return the :c:member:`~PyTypeObject.tp_flags` member of *type*. This function is primarily
43 meant for use with ``Py_LIMITED_API``; the individual flag bits are
44 guaranteed to be stable across Python releases, but access to
45 :c:member:`~PyTypeObject.tp_flags` itself is not part of the :ref:`limited API <limited-c-api>`.
46
47 .. versionadded:: 3.2
48
49 .. versionchanged:: 3.4
50 The return type is now ``unsigned long`` rather than ``long``.
51
52
53 .. c:function:: PyObject* PyType_GetDict(PyTypeObject* type)
54
55 Return the type object's internal namespace, which is otherwise only
56 exposed via a read-only proxy (:attr:`cls.__dict__ <type.__dict__>`).
57 This is a
58 replacement for accessing :c:member:`~PyTypeObject.tp_dict` directly.
59 The returned dictionary must be treated as read-only.
60
61 This function is meant for specific embedding and language-binding cases,
62 where direct access to the dict is necessary and indirect access
63 (e.g. via the proxy or :c:func:`PyObject_GetAttr`) isn't adequate.
64
65 Extension modules should continue to use ``tp_dict``,
66 directly or indirectly, when setting up their own types.
67
68 .. versionadded:: 3.12
69
70
71 .. c:function:: void PyType_Modified(PyTypeObject *type)
72
73 Invalidate the internal lookup cache for the type and all of its
74 subtypes. This function must be called after any manual
75 modification of the attributes or base classes of the type.
76
77
78 .. c:function:: int PyType_AddWatcher(PyType_WatchCallback callback)
79
80 Register *callback* as a type watcher. Return a non-negative integer ID
81 which must be passed to future calls to :c:func:`PyType_Watch`. In case of
82 error (e.g. no more watcher IDs available), return ``-1`` and set an
83 exception.
84
85 In free-threaded builds, :c:func:`PyType_AddWatcher` is not thread-safe,
86 so it must be called at start up (before spawning the first thread).
87
88 .. versionadded:: 3.12
89
90
91 .. c:function:: int PyType_ClearWatcher(int watcher_id)
92
93 Clear watcher identified by *watcher_id* (previously returned from
94 :c:func:`PyType_AddWatcher`). Return ``0`` on success, ``-1`` on error (e.g.
95 if *watcher_id* was never registered.)
96
97 An extension should never call ``PyType_ClearWatcher`` with a *watcher_id*
98 that was not returned to it by a previous call to
99 :c:func:`PyType_AddWatcher`.
100
101 .. versionadded:: 3.12
102
103
104 .. c:function:: int PyType_Watch(int watcher_id, PyObject *type)
105
106 Mark *type* as watched. The callback granted *watcher_id* by
107 :c:func:`PyType_AddWatcher` will be called whenever
108 :c:func:`PyType_Modified` reports a change to *type*. (The callback may be
109 called only once for a series of consecutive modifications to *type*, if
110 :c:func:`!_PyType_Lookup` is not called on *type* between the modifications;
111 this is an implementation detail and subject to change.)
112
113 An extension should never call ``PyType_Watch`` with a *watcher_id* that was
114 not returned to it by a previous call to :c:func:`PyType_AddWatcher`.
115
116 .. versionadded:: 3.12
117
118
119 .. c:function:: int PyType_Unwatch(int watcher_id, PyObject *type)
120
121 Mark *type* as not watched. This undoes a previous call to
122 :c:func:`PyType_Watch`. *type* must not be ``NULL``.
123
124 An extension should never call this function with a *watcher_id* that was
125 not returned to it by a previous call to :c:func:`PyType_AddWatcher`.
126
127 On success, this function returns ``0``. On failure, this function returns
128 ``-1`` with an exception set.
129
130 .. versionadded:: 3.12
131
132
133 .. c:type:: int (*PyType_WatchCallback)(PyObject *type)
134
135 Type of a type-watcher callback function.
136
137 The callback must not modify *type* or cause :c:func:`PyType_Modified` to be
138 called on *type* or any type in its MRO; violating this rule could cause
139 infinite recursion.
140
141 .. versionadded:: 3.12
142
143
144 .. c:function:: int PyType_HasFeature(PyTypeObject *o, int feature)
145
146 Return non-zero if the type object *o* sets the feature *feature*.
147 Type features are denoted by single bit flags.
148
149
150 .. c:function:: int PyType_FastSubclass(PyTypeObject *type, int flag)
151
152 Return non-zero if the type object *type* sets the subclass flag *flag*.
153 Subclass flags are denoted by
154 :c:macro:`Py_TPFLAGS_*_SUBCLASS <Py_TPFLAGS_LONG_SUBCLASS>`.
155 This function is used by many ``_Check`` functions for common types.
156
157 .. seealso::
158 :c:func:`PyObject_TypeCheck`, which is used as a slower alternative in
159 ``_Check`` functions for types that don't come with subclass flags.
160
161
162 .. c:function:: int PyType_IS_GC(PyTypeObject *o)
163
164 Return true if the type object includes support for the cycle detector; this
165 tests the type flag :c:macro:`Py_TPFLAGS_HAVE_GC`.
166
167
168 .. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
169
170 Return true if *a* is a subtype of *b*.
171
172 This function only checks for actual subtypes, which means that
173 :meth:`~type.__subclasscheck__` is not called on *b*. Call
174 :c:func:`PyObject_IsSubclass` to do the same check that :func:`issubclass`
175 would do.
176
177
178 .. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
179
180 Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type object. Use
181 Python's default memory allocation mechanism to allocate a new instance and
182 initialize all its contents to ``NULL``.
183
184
185 .. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
186
187 Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type object. Create a
188 new instance using the type's :c:member:`~PyTypeObject.tp_alloc` slot.
189
190
191 .. c:function:: int PyType_Ready(PyTypeObject *type)
192
193 Finalize a type object. This should be called on all type objects to finish
194 their initialization. This function is responsible for adding inherited slots
195 from a type's base class. Return ``0`` on success, or return ``-1`` and sets an
196 exception on error.
197
198 .. note::
199 If some of the base classes implements the GC protocol and the provided
200 type does not include the :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags, then
201 the GC protocol will be automatically implemented from its parents. On
202 the contrary, if the type being created does include
203 :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags then it **must** implement the
204 GC protocol itself by at least implementing the
205 :c:member:`~PyTypeObject.tp_traverse` handle.
206
207
208 .. c:function:: PyObject* PyType_GetName(PyTypeObject *type)
209
210 Return the type's name. Equivalent to getting the type's
211 :attr:`~type.__name__` attribute.
212
213 .. versionadded:: 3.11
214
215
216 .. c:function:: PyObject* PyType_GetQualName(PyTypeObject *type)
217
218 Return the type's qualified name. Equivalent to getting the
219 type's :attr:`~type.__qualname__` attribute.
220
221 .. versionadded:: 3.11
222
223 .. c:function:: PyObject* PyType_GetFullyQualifiedName(PyTypeObject *type)
224
225 Return the type's fully qualified name. Equivalent to
226 ``f"{type.__module__}.{type.__qualname__}"``, or :attr:`type.__qualname__`
227 if :attr:`type.__module__` is not a string or is equal to ``"builtins"``.
228
229 .. versionadded:: 3.13
230
231
232 .. c:function:: PyObject* PyType_GetModuleName(PyTypeObject *type)
233
234 Return the type's module name. Equivalent to getting the
235 :attr:`type.__module__` attribute.
236
237 .. versionadded:: 3.13
238
239
240 .. c:function:: void* PyType_GetSlot(PyTypeObject *type, int slot)
241
242 Return the function pointer stored in the given slot. If the
243 result is ``NULL``, this indicates that either the slot is ``NULL``,
244 or that the function was called with invalid parameters.
245 Callers will typically cast the result pointer into the appropriate
246 function type.
247
248 See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument.
249
250 .. versionadded:: 3.4
251
252 .. versionchanged:: 3.10
253 :c:func:`PyType_GetSlot` can now accept all types.
254 Previously, it was limited to :ref:`heap types <heap-types>`.
255
256
257 .. c:function:: PyObject* PyType_GetModule(PyTypeObject *type)
258
259 Return the module object associated with the given type when the type was
260 created using :c:func:`PyType_FromModuleAndSpec`.
261
262 If no module is associated with the given type, sets :py:class:`TypeError`
263 and returns ``NULL``.
264
265 This function is usually used to get the module in which a method is defined.
266 Note that in such a method, ``PyType_GetModule(Py_TYPE(self))``
267 may not return the intended result.
268 ``Py_TYPE(self)`` may be a *subclass* of the intended class, and subclasses
269 are not necessarily defined in the same module as their superclass.
270 See :c:type:`PyCMethod` to get the class that defines the method.
271 See :c:func:`PyType_GetModuleByDef` for cases when :c:type:`!PyCMethod` cannot
272 be used.
273
274 .. versionadded:: 3.9
275
276
277 .. c:function:: void* PyType_GetModuleState(PyTypeObject *type)
278
279 Return the state of the module object associated with the given type.
280 This is a shortcut for calling :c:func:`PyModule_GetState()` on the result
281 of :c:func:`PyType_GetModule`.
282
283 If no module is associated with the given type, sets :py:class:`TypeError`
284 and returns ``NULL``.
285
286 If the *type* has an associated module but its state is ``NULL``,
287 returns ``NULL`` without setting an exception.
288
289 .. versionadded:: 3.9
290
291
292 .. c:function:: PyObject* PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
293
294 Find the first superclass whose module was created from
295 the given :c:type:`PyModuleDef` *def*, and return that module.
296
297 If no module is found, raises a :py:class:`TypeError` and returns ``NULL``.
298
299 This function is intended to be used together with
300 :c:func:`PyModule_GetState()` to get module state from slot methods (such as
301 :c:member:`~PyTypeObject.tp_init` or :c:member:`~PyNumberMethods.nb_add`)
302 and other places where a method's defining class cannot be passed using the
303 :c:type:`PyCMethod` calling convention.
304
305 The returned reference is :term:`borrowed <borrowed reference>` from *type*,
306 and will be valid as long as you hold a reference to *type*.
307 Do not release it with :c:func:`Py_DECREF` or similar.
308
309 .. versionadded:: 3.11
310
311
312 .. c:function:: int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
313
314 Attempt to assign a version tag to the given type.
315
316 Returns 1 if the type already had a valid version tag or a new one was
317 assigned, or 0 if a new tag could not be assigned.
318
319 .. versionadded:: 3.12
320
321
322 .. c:function:: int PyType_SUPPORTS_WEAKREFS(PyTypeObject *type)
323
324 Return true if instances of *type* support creating weak references, false
325 otherwise. This function always succeeds. *type* must not be ``NULL``.
326
327 .. seealso::
328 * :ref:`weakrefobjects`
329 * :py:mod:`weakref`
330
331
332 Creating Heap-Allocated Types
333 .............................
334
335 The following functions and structs are used to create
336 :ref:`heap types <heap-types>`.
337
338 .. c:function:: PyObject* PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases)
339
340 Create and return a :ref:`heap type <heap-types>` from the *spec*
341 (see :c:macro:`Py_TPFLAGS_HEAPTYPE`).
342
343 The metaclass *metaclass* is used to construct the resulting type object.
344 When *metaclass* is ``NULL``, the metaclass is derived from *bases*
345 (or *Py_tp_base[s]* slots if *bases* is ``NULL``, see below).
346
347 Metaclasses that override :c:member:`~PyTypeObject.tp_new` are not
348 supported, except if ``tp_new`` is ``NULL``.
349 (For backwards compatibility, other ``PyType_From*`` functions allow
350 such metaclasses. They ignore ``tp_new``, which may result in incomplete
351 initialization. This is deprecated and in Python 3.14+ such metaclasses will
352 not be supported.)
353
354 The *bases* argument can be used to specify base classes; it can either
355 be only one class or a tuple of classes.
356 If *bases* is ``NULL``, the *Py_tp_bases* slot is used instead.
357 If that also is ``NULL``, the *Py_tp_base* slot is used instead.
358 If that also is ``NULL``, the new type derives from :class:`object`.
359
360 The *module* argument can be used to record the module in which the new
361 class is defined. It must be a module object or ``NULL``.
362 If not ``NULL``, the module is associated with the new type and can later be
363 retrieved with :c:func:`PyType_GetModule`.
364 The associated module is not inherited by subclasses; it must be specified
365 for each class individually.
366
367 This function calls :c:func:`PyType_Ready` on the new type.
368
369 Note that this function does *not* fully match the behavior of
370 calling :py:class:`type() <type>` or using the :keyword:`class` statement.
371 With user-provided base types or metaclasses, prefer
372 :ref:`calling <capi-call>` :py:class:`type` (or the metaclass)
373 over ``PyType_From*`` functions.
374 Specifically:
375
376 * :py:meth:`~object.__new__` is not called on the new class
377 (and it must be set to ``type.__new__``).
378 * :py:meth:`~object.__init__` is not called on the new class.
379 * :py:meth:`~object.__init_subclass__` is not called on any bases.
380 * :py:meth:`~object.__set_name__` is not called on new descriptors.
381
382 .. versionadded:: 3.12
383
384
385 .. c:function:: PyObject* PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
386
387 Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``.
388
389 .. versionadded:: 3.9
390
391 .. versionchanged:: 3.10
392
393 The function now accepts a single class as the *bases* argument and
394 ``NULL`` as the ``tp_doc`` slot.
395
396 .. versionchanged:: 3.12
397
398 The function now finds and uses a metaclass corresponding to the provided
399 base classes. Previously, only :class:`type` instances were returned.
400
401 The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
402 which may result in incomplete initialization.
403 Creating classes whose metaclass overrides
404 :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
405 will be no longer allowed.
406
407
408 .. c:function:: PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
409
410 Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``.
411
412 .. versionadded:: 3.3
413
414 .. versionchanged:: 3.12
415
416 The function now finds and uses a metaclass corresponding to the provided
417 base classes. Previously, only :class:`type` instances were returned.
418
419 The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
420 which may result in incomplete initialization.
421 Creating classes whose metaclass overrides
422 :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
423 will be no longer allowed.
424
425
426 .. c:function:: PyObject* PyType_FromSpec(PyType_Spec *spec)
427
428 Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``.
429
430 .. versionchanged:: 3.12
431
432 The function now finds and uses a metaclass corresponding to the
433 base classes provided in *Py_tp_base[s]* slots.
434 Previously, only :class:`type` instances were returned.
435
436 The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
437 which may result in incomplete initialization.
438 Creating classes whose metaclass overrides
439 :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
440 will be no longer allowed.
441
442 .. raw:: html
443
444 <!-- Keep old URL fragments working (see gh-97908) -->
445 <span id='c.PyType_Spec.PyType_Spec.name'></span>
446 <span id='c.PyType_Spec.PyType_Spec.basicsize'></span>
447 <span id='c.PyType_Spec.PyType_Spec.itemsize'></span>
448 <span id='c.PyType_Spec.PyType_Spec.flags'></span>
449 <span id='c.PyType_Spec.PyType_Spec.slots'></span>
450
451 .. c:type:: PyType_Spec
452
453 Structure defining a type's behavior.
454
455 .. c:member:: const char* name
456
457 Name of the type, used to set :c:member:`PyTypeObject.tp_name`.
458
459 .. c:member:: int basicsize
460
461 If positive, specifies the size of the instance in bytes.
462 It is used to set :c:member:`PyTypeObject.tp_basicsize`.
463
464 If zero, specifies that :c:member:`~PyTypeObject.tp_basicsize`
465 should be inherited.
466
467 If negative, the absolute value specifies how much space instances of the
468 class need *in addition* to the superclass.
469 Use :c:func:`PyObject_GetTypeData` to get a pointer to subclass-specific
470 memory reserved this way.
471 For negative :c:member:`!basicsize`, Python will insert padding when
472 needed to meet :c:member:`~PyTypeObject.tp_basicsize`'s alignment
473 requirements.
474
475 .. versionchanged:: 3.12
476
477 Previously, this field could not be negative.
478
479 .. c:member:: int itemsize
480
481 Size of one element of a variable-size type, in bytes.
482 Used to set :c:member:`PyTypeObject.tp_itemsize`.
483 See ``tp_itemsize`` documentation for caveats.
484
485 If zero, :c:member:`~PyTypeObject.tp_itemsize` is inherited.
486 Extending arbitrary variable-sized classes is dangerous,
487 since some types use a fixed offset for variable-sized memory,
488 which can then overlap fixed-sized memory used by a subclass.
489 To help prevent mistakes, inheriting ``itemsize`` is only possible
490 in the following situations:
491
492 - The base is not variable-sized (its
493 :c:member:`~PyTypeObject.tp_itemsize`).
494 - The requested :c:member:`PyType_Spec.basicsize` is positive,
495 suggesting that the memory layout of the base class is known.
496 - The requested :c:member:`PyType_Spec.basicsize` is zero,
497 suggesting that the subclass does not access the instance's memory
498 directly.
499 - With the :c:macro:`Py_TPFLAGS_ITEMS_AT_END` flag.
500
501 .. c:member:: unsigned int flags
502
503 Type flags, used to set :c:member:`PyTypeObject.tp_flags`.
504
505 If the ``Py_TPFLAGS_HEAPTYPE`` flag is not set,
506 :c:func:`PyType_FromSpecWithBases` sets it automatically.
507
508 .. c:member:: PyType_Slot *slots
509
510 Array of :c:type:`PyType_Slot` structures.
511 Terminated by the special slot value ``{0, NULL}``.
512
513 Each slot ID should be specified at most once.
514
515 .. raw:: html
516
517 <!-- Keep old URL fragments working (see gh-97908) -->
518 <span id='c.PyType_Slot.PyType_Slot.slot'></span>
519 <span id='c.PyType_Slot.PyType_Slot.pfunc'></span>
520
521 .. c:type:: PyType_Slot
522
523 Structure defining optional functionality of a type, containing a slot ID
524 and a value pointer.
525
526 .. c:member:: int slot
527
528 A slot ID.
529
530 Slot IDs are named like the field names of the structures
531 :c:type:`PyTypeObject`, :c:type:`PyNumberMethods`,
532 :c:type:`PySequenceMethods`, :c:type:`PyMappingMethods` and
533 :c:type:`PyAsyncMethods` with an added ``Py_`` prefix.
534 For example, use:
535
536 * ``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`
537 * ``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`
538 * ``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`
539
540 The following “offset” fields cannot be set using :c:type:`PyType_Slot`:
541
542 * :c:member:`~PyTypeObject.tp_weaklistoffset`
543 (use :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` instead if possible)
544 * :c:member:`~PyTypeObject.tp_dictoffset`
545 (use :c:macro:`Py_TPFLAGS_MANAGED_DICT` instead if possible)
546 * :c:member:`~PyTypeObject.tp_vectorcall_offset`
547 (use ``"__vectorcalloffset__"`` in
548 :ref:`PyMemberDef <pymemberdef-offsets>`)
549
550 If it is not possible to switch to a ``MANAGED`` flag (for example,
551 for vectorcall or to support Python older than 3.12), specify the
552 offset in :c:member:`Py_tp_members <PyTypeObject.tp_members>`.
553 See :ref:`PyMemberDef documentation <pymemberdef-offsets>`
554 for details.
555
556 The following fields cannot be set at all when creating a heap type:
557
558 * :c:member:`~PyTypeObject.tp_vectorcall`
559 (use :c:member:`~PyTypeObject.tp_new` and/or
560 :c:member:`~PyTypeObject.tp_init`)
561
562 * Internal fields:
563 :c:member:`~PyTypeObject.tp_dict`,
564 :c:member:`~PyTypeObject.tp_mro`,
565 :c:member:`~PyTypeObject.tp_cache`,
566 :c:member:`~PyTypeObject.tp_subclasses`, and
567 :c:member:`~PyTypeObject.tp_weaklist`.
568
569 Setting :c:data:`Py_tp_bases` or :c:data:`Py_tp_base` may be
570 problematic on some platforms.
571 To avoid issues, use the *bases* argument of
572 :c:func:`PyType_FromSpecWithBases` instead.
573
574 .. versionchanged:: 3.9
575 Slots in :c:type:`PyBufferProcs` may be set in the unlimited API.
576
577 .. versionchanged:: 3.11
578 :c:member:`~PyBufferProcs.bf_getbuffer` and
579 :c:member:`~PyBufferProcs.bf_releasebuffer` are now available
580 under the :ref:`limited API <limited-c-api>`.
581
582 .. c:member:: void *pfunc
583
584 The desired value of the slot. In most cases, this is a pointer
585 to a function.
586
587 Slots other than ``Py_tp_doc`` may not be ``NULL``.