• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _typeobjects:
4
5Type 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   .. versionadded:: 3.12
86
87
88.. c:function:: int PyType_ClearWatcher(int watcher_id)
89
90   Clear watcher identified by *watcher_id* (previously returned from
91   :c:func:`PyType_AddWatcher`). Return ``0`` on success, ``-1`` on error (e.g.
92   if *watcher_id* was never registered.)
93
94   An extension should never call ``PyType_ClearWatcher`` with a *watcher_id*
95   that was not returned to it by a previous call to
96   :c:func:`PyType_AddWatcher`.
97
98   .. versionadded:: 3.12
99
100
101.. c:function:: int PyType_Watch(int watcher_id, PyObject *type)
102
103   Mark *type* as watched. The callback granted *watcher_id* by
104   :c:func:`PyType_AddWatcher` will be called whenever
105   :c:func:`PyType_Modified` reports a change to *type*. (The callback may be
106   called only once for a series of consecutive modifications to *type*, if
107   :c:func:`!_PyType_Lookup` is not called on *type* between the modifications;
108   this is an implementation detail and subject to change.)
109
110   An extension should never call ``PyType_Watch`` with a *watcher_id* that was
111   not returned to it by a previous call to :c:func:`PyType_AddWatcher`.
112
113   .. versionadded:: 3.12
114
115
116.. c:type:: int (*PyType_WatchCallback)(PyObject *type)
117
118   Type of a type-watcher callback function.
119
120   The callback must not modify *type* or cause :c:func:`PyType_Modified` to be
121   called on *type* or any type in its MRO; violating this rule could cause
122   infinite recursion.
123
124   .. versionadded:: 3.12
125
126
127.. c:function:: int PyType_HasFeature(PyTypeObject *o, int feature)
128
129   Return non-zero if the type object *o* sets the feature *feature*.
130   Type features are denoted by single bit flags.
131
132
133.. c:function:: int PyType_IS_GC(PyTypeObject *o)
134
135   Return true if the type object includes support for the cycle detector; this
136   tests the type flag :c:macro:`Py_TPFLAGS_HAVE_GC`.
137
138
139.. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
140
141   Return true if *a* is a subtype of *b*.
142
143   This function only checks for actual subtypes, which means that
144   :meth:`~type.__subclasscheck__` is not called on *b*.  Call
145   :c:func:`PyObject_IsSubclass` to do the same check that :func:`issubclass`
146   would do.
147
148
149.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
150
151   Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type object.  Use
152   Python's default memory allocation mechanism to allocate a new instance and
153   initialize all its contents to ``NULL``.
154
155.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
156
157   Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type object.  Create a
158   new instance using the type's :c:member:`~PyTypeObject.tp_alloc` slot.
159
160.. c:function:: int PyType_Ready(PyTypeObject *type)
161
162   Finalize a type object.  This should be called on all type objects to finish
163   their initialization.  This function is responsible for adding inherited slots
164   from a type's base class.  Return ``0`` on success, or return ``-1`` and sets an
165   exception on error.
166
167   .. note::
168       If some of the base classes implements the GC protocol and the provided
169       type does not include the :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags, then
170       the GC protocol will be automatically implemented from its parents. On
171       the contrary, if the type being created does include
172       :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags then it **must** implement the
173       GC protocol itself by at least implementing the
174       :c:member:`~PyTypeObject.tp_traverse` handle.
175
176.. c:function:: PyObject* PyType_GetName(PyTypeObject *type)
177
178   Return the type's name. Equivalent to getting the type's
179   :attr:`~type.__name__` attribute.
180
181   .. versionadded:: 3.11
182
183.. c:function:: PyObject* PyType_GetQualName(PyTypeObject *type)
184
185   Return the type's qualified name. Equivalent to getting the
186   type's :attr:`~type.__qualname__` attribute.
187
188   .. versionadded:: 3.11
189
190.. c:function:: PyObject* PyType_GetFullyQualifiedName(PyTypeObject *type)
191
192   Return the type's fully qualified name. Equivalent to
193   ``f"{type.__module__}.{type.__qualname__}"``, or :attr:`type.__qualname__`
194   if :attr:`type.__module__` is not a string or is equal to ``"builtins"``.
195
196   .. versionadded:: 3.13
197
198.. c:function:: PyObject* PyType_GetModuleName(PyTypeObject *type)
199
200   Return the type's module name. Equivalent to getting the
201   :attr:`type.__module__` attribute.
202
203   .. versionadded:: 3.13
204
205.. c:function:: void* PyType_GetSlot(PyTypeObject *type, int slot)
206
207   Return the function pointer stored in the given slot. If the
208   result is ``NULL``, this indicates that either the slot is ``NULL``,
209   or that the function was called with invalid parameters.
210   Callers will typically cast the result pointer into the appropriate
211   function type.
212
213   See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument.
214
215   .. versionadded:: 3.4
216
217   .. versionchanged:: 3.10
218      :c:func:`PyType_GetSlot` can now accept all types.
219      Previously, it was limited to :ref:`heap types <heap-types>`.
220
221.. c:function:: PyObject* PyType_GetModule(PyTypeObject *type)
222
223   Return the module object associated with the given type when the type was
224   created using :c:func:`PyType_FromModuleAndSpec`.
225
226   If no module is associated with the given type, sets :py:class:`TypeError`
227   and returns ``NULL``.
228
229   This function is usually used to get the module in which a method is defined.
230   Note that in such a method, ``PyType_GetModule(Py_TYPE(self))``
231   may not return the intended result.
232   ``Py_TYPE(self)`` may be a *subclass* of the intended class, and subclasses
233   are not necessarily defined in the same module as their superclass.
234   See :c:type:`PyCMethod` to get the class that defines the method.
235   See :c:func:`PyType_GetModuleByDef` for cases when :c:type:`!PyCMethod` cannot
236   be used.
237
238   .. versionadded:: 3.9
239
240.. c:function:: void* PyType_GetModuleState(PyTypeObject *type)
241
242   Return the state of the module object associated with the given type.
243   This is a shortcut for calling :c:func:`PyModule_GetState()` on the result
244   of :c:func:`PyType_GetModule`.
245
246   If no module is associated with the given type, sets :py:class:`TypeError`
247   and returns ``NULL``.
248
249   If the *type* has an associated module but its state is ``NULL``,
250   returns ``NULL`` without setting an exception.
251
252   .. versionadded:: 3.9
253
254.. c:function:: PyObject* PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
255
256   Find the first superclass whose module was created from
257   the given :c:type:`PyModuleDef` *def*, and return that module.
258
259   If no module is found, raises a :py:class:`TypeError` and returns ``NULL``.
260
261   This function is intended to be used together with
262   :c:func:`PyModule_GetState()` to get module state from slot methods (such as
263   :c:member:`~PyTypeObject.tp_init` or :c:member:`~PyNumberMethods.nb_add`)
264   and other places where a method's defining class cannot be passed using the
265   :c:type:`PyCMethod` calling convention.
266
267   .. versionadded:: 3.11
268
269.. c:function:: int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
270
271   Attempt to assign a version tag to the given type.
272
273   Returns 1 if the type already had a valid version tag or a new one was
274   assigned, or 0 if a new tag could not be assigned.
275
276   .. versionadded:: 3.12
277
278
279Creating Heap-Allocated Types
280.............................
281
282The following functions and structs are used to create
283:ref:`heap types <heap-types>`.
284
285.. c:function:: PyObject* PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases)
286
287   Create and return a :ref:`heap type <heap-types>` from the *spec*
288   (see :c:macro:`Py_TPFLAGS_HEAPTYPE`).
289
290   The metaclass *metaclass* is used to construct the resulting type object.
291   When *metaclass* is ``NULL``, the metaclass is derived from *bases*
292   (or *Py_tp_base[s]* slots if *bases* is ``NULL``, see below).
293
294   Metaclasses that override :c:member:`~PyTypeObject.tp_new` are not
295   supported, except if ``tp_new`` is ``NULL``.
296   (For backwards compatibility, other ``PyType_From*`` functions allow
297   such metaclasses. They ignore ``tp_new``, which may result in incomplete
298   initialization. This is deprecated and in Python 3.14+ such metaclasses will
299   not be supported.)
300
301   The *bases* argument can be used to specify base classes; it can either
302   be only one class or a tuple of classes.
303   If *bases* is ``NULL``, the *Py_tp_bases* slot is used instead.
304   If that also is ``NULL``, the *Py_tp_base* slot is used instead.
305   If that also is ``NULL``, the new type derives from :class:`object`.
306
307   The *module* argument can be used to record the module in which the new
308   class is defined. It must be a module object or ``NULL``.
309   If not ``NULL``, the module is associated with the new type and can later be
310   retrieved with :c:func:`PyType_GetModule`.
311   The associated module is not inherited by subclasses; it must be specified
312   for each class individually.
313
314   This function calls :c:func:`PyType_Ready` on the new type.
315
316   Note that this function does *not* fully match the behavior of
317   calling :py:class:`type() <type>` or using the :keyword:`class` statement.
318   With user-provided base types or metaclasses, prefer
319   :ref:`calling <capi-call>` :py:class:`type` (or the metaclass)
320   over ``PyType_From*`` functions.
321   Specifically:
322
323   * :py:meth:`~object.__new__` is not called on the new class
324     (and it must be set to ``type.__new__``).
325   * :py:meth:`~object.__init__` is not called on the new class.
326   * :py:meth:`~object.__init_subclass__` is not called on any bases.
327   * :py:meth:`~object.__set_name__` is not called on new descriptors.
328
329   .. versionadded:: 3.12
330
331.. c:function:: PyObject* PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
332
333   Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``.
334
335   .. versionadded:: 3.9
336
337   .. versionchanged:: 3.10
338
339      The function now accepts a single class as the *bases* argument and
340      ``NULL`` as the ``tp_doc`` slot.
341
342   .. versionchanged:: 3.12
343
344      The function now finds and uses a metaclass corresponding to the provided
345      base classes.  Previously, only :class:`type` instances were returned.
346
347      The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
348      which may result in incomplete initialization.
349      Creating classes whose metaclass overrides
350      :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
351      will be no longer allowed.
352
353.. c:function:: PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
354
355   Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``.
356
357   .. versionadded:: 3.3
358
359   .. versionchanged:: 3.12
360
361      The function now finds and uses a metaclass corresponding to the provided
362      base classes.  Previously, only :class:`type` instances were returned.
363
364      The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
365      which may result in incomplete initialization.
366      Creating classes whose metaclass overrides
367      :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
368      will be no longer allowed.
369
370.. c:function:: PyObject* PyType_FromSpec(PyType_Spec *spec)
371
372   Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``.
373
374   .. versionchanged:: 3.12
375
376      The function now finds and uses a metaclass corresponding to the
377      base classes provided in *Py_tp_base[s]* slots.
378      Previously, only :class:`type` instances were returned.
379
380      The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*.
381      which may result in incomplete initialization.
382      Creating classes whose metaclass overrides
383      :c:member:`~PyTypeObject.tp_new` is deprecated and in Python 3.14+ it
384      will be no longer allowed.
385
386.. raw:: html
387
388   <!-- Keep old URL fragments working (see gh-97908) -->
389   <span id='c.PyType_Spec.PyType_Spec.name'></span>
390   <span id='c.PyType_Spec.PyType_Spec.basicsize'></span>
391   <span id='c.PyType_Spec.PyType_Spec.itemsize'></span>
392   <span id='c.PyType_Spec.PyType_Spec.flags'></span>
393   <span id='c.PyType_Spec.PyType_Spec.slots'></span>
394
395.. c:type:: PyType_Spec
396
397   Structure defining a type's behavior.
398
399   .. c:member:: const char* name
400
401      Name of the type, used to set :c:member:`PyTypeObject.tp_name`.
402
403   .. c:member:: int basicsize
404
405      If positive, specifies the size of the instance in bytes.
406      It is used to set :c:member:`PyTypeObject.tp_basicsize`.
407
408      If zero, specifies that :c:member:`~PyTypeObject.tp_basicsize`
409      should be inherited.
410
411      If negative, the absolute value specifies how much space instances of the
412      class need *in addition* to the superclass.
413      Use :c:func:`PyObject_GetTypeData` to get a pointer to subclass-specific
414      memory reserved this way.
415
416      .. versionchanged:: 3.12
417
418         Previously, this field could not be negative.
419
420   .. c:member:: int itemsize
421
422      Size of one element of a variable-size type, in bytes.
423      Used to set :c:member:`PyTypeObject.tp_itemsize`.
424      See ``tp_itemsize`` documentation for caveats.
425
426      If zero, :c:member:`~PyTypeObject.tp_itemsize` is inherited.
427      Extending arbitrary variable-sized classes is dangerous,
428      since some types use a fixed offset for variable-sized memory,
429      which can then overlap fixed-sized memory used by a subclass.
430      To help prevent mistakes, inheriting ``itemsize`` is only possible
431      in the following situations:
432
433      - The base is not variable-sized (its
434        :c:member:`~PyTypeObject.tp_itemsize`).
435      - The requested :c:member:`PyType_Spec.basicsize` is positive,
436        suggesting that the memory layout of the base class is known.
437      - The requested :c:member:`PyType_Spec.basicsize` is zero,
438        suggesting that the subclass does not access the instance's memory
439        directly.
440      - With the :c:macro:`Py_TPFLAGS_ITEMS_AT_END` flag.
441
442   .. c:member:: unsigned int flags
443
444      Type flags, used to set :c:member:`PyTypeObject.tp_flags`.
445
446      If the ``Py_TPFLAGS_HEAPTYPE`` flag is not set,
447      :c:func:`PyType_FromSpecWithBases` sets it automatically.
448
449   .. c:member:: PyType_Slot *slots
450
451      Array of :c:type:`PyType_Slot` structures.
452      Terminated by the special slot value ``{0, NULL}``.
453
454      Each slot ID should be specified at most once.
455
456.. raw:: html
457
458   <!-- Keep old URL fragments working (see gh-97908) -->
459   <span id='c.PyType_Slot.PyType_Slot.slot'></span>
460   <span id='c.PyType_Slot.PyType_Slot.pfunc'></span>
461
462.. c:type:: PyType_Slot
463
464   Structure defining optional functionality of a type, containing a slot ID
465   and a value pointer.
466
467   .. c:member:: int slot
468
469      A slot ID.
470
471      Slot IDs are named like the field names of the structures
472      :c:type:`PyTypeObject`, :c:type:`PyNumberMethods`,
473      :c:type:`PySequenceMethods`, :c:type:`PyMappingMethods` and
474      :c:type:`PyAsyncMethods` with an added ``Py_`` prefix.
475      For example, use:
476
477      * ``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`
478      * ``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`
479      * ``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`
480
481      The following “offset” fields cannot be set using :c:type:`PyType_Slot`:
482
483      * :c:member:`~PyTypeObject.tp_weaklistoffset`
484        (use :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` instead if possible)
485      * :c:member:`~PyTypeObject.tp_dictoffset`
486        (use :c:macro:`Py_TPFLAGS_MANAGED_DICT` instead if possible)
487      * :c:member:`~PyTypeObject.tp_vectorcall_offset`
488        (use ``"__vectorcalloffset__"`` in
489        :ref:`PyMemberDef <pymemberdef-offsets>`)
490
491      If it is not possible to switch to a ``MANAGED`` flag (for example,
492      for vectorcall or to support Python older than 3.12), specify the
493      offset in :c:member:`Py_tp_members <PyTypeObject.tp_members>`.
494      See :ref:`PyMemberDef documentation <pymemberdef-offsets>`
495      for details.
496
497      The following fields cannot be set at all when creating a heap type:
498
499      * :c:member:`~PyTypeObject.tp_vectorcall`
500        (use :c:member:`~PyTypeObject.tp_new` and/or
501        :c:member:`~PyTypeObject.tp_init`)
502
503      * Internal fields:
504        :c:member:`~PyTypeObject.tp_dict`,
505        :c:member:`~PyTypeObject.tp_mro`,
506        :c:member:`~PyTypeObject.tp_cache`,
507        :c:member:`~PyTypeObject.tp_subclasses`, and
508        :c:member:`~PyTypeObject.tp_weaklist`.
509
510      Setting :c:data:`Py_tp_bases` or :c:data:`Py_tp_base` may be
511      problematic on some platforms.
512      To avoid issues, use the *bases* argument of
513      :c:func:`PyType_FromSpecWithBases` instead.
514
515      .. versionchanged:: 3.9
516         Slots in :c:type:`PyBufferProcs` may be set in the unlimited API.
517
518      .. versionchanged:: 3.11
519         :c:member:`~PyBufferProcs.bf_getbuffer` and
520         :c:member:`~PyBufferProcs.bf_releasebuffer` are now available
521         under the :ref:`limited API <limited-c-api>`.
522
523   .. c:member:: void *pfunc
524
525      The desired value of the slot. In most cases, this is a pointer
526      to a function.
527
528      Slots other than ``Py_tp_doc`` may not be ``NULL``.
529