• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _common-structs:
4
5Common Object Structures
6========================
7
8There are a large number of structures which are used in the definition of
9object types for Python.  This section describes these structures and how they
10are used.
11
12
13Base object types and macros
14----------------------------
15
16All Python objects ultimately share a small number of fields at the beginning
17of the object's representation in memory.  These are represented by the
18:c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn,
19by the expansions of some macros also used, whether directly or indirectly, in
20the definition of all other Python objects.  Additional macros can be found
21under :ref:`reference counting <countingrefs>`.
22
23
24.. c:type:: PyObject
25
26   All object types are extensions of this type.  This is a type which
27   contains the information Python needs to treat a pointer to an object as an
28   object.  In a normal "release" build, it contains only the object's
29   reference count and a pointer to the corresponding type object.
30   Nothing is actually declared to be a :c:type:`PyObject`, but every pointer
31   to a Python object can be cast to a :c:expr:`PyObject*`.  Access to the
32   members must be done by using the macros :c:macro:`Py_REFCNT` and
33   :c:macro:`Py_TYPE`.
34
35
36.. c:type:: PyVarObject
37
38   This is an extension of :c:type:`PyObject` that adds the :c:member:`~PyVarObject.ob_size`
39   field.  This is only used for objects that have some notion of *length*.
40   This type does not often appear in the Python/C API.
41   Access to the members must be done by using the macros
42   :c:macro:`Py_REFCNT`, :c:macro:`Py_TYPE`, and :c:macro:`Py_SIZE`.
43
44
45.. c:macro:: PyObject_HEAD
46
47   This is a macro used when declaring new types which represent objects
48   without a varying length.  The PyObject_HEAD macro expands to::
49
50      PyObject ob_base;
51
52   See documentation of :c:type:`PyObject` above.
53
54
55.. c:macro:: PyObject_VAR_HEAD
56
57   This is a macro used when declaring new types which represent objects
58   with a length that varies from instance to instance.
59   The PyObject_VAR_HEAD macro expands to::
60
61      PyVarObject ob_base;
62
63   See documentation of :c:type:`PyVarObject` above.
64
65
66.. c:function:: int Py_Is(PyObject *x, PyObject *y)
67
68   Test if the *x* object is the *y* object, the same as ``x is y`` in Python.
69
70   .. versionadded:: 3.10
71
72
73.. c:function:: int Py_IsNone(PyObject *x)
74
75   Test if an object is the ``None`` singleton,
76   the same as ``x is None`` in Python.
77
78   .. versionadded:: 3.10
79
80
81.. c:function:: int Py_IsTrue(PyObject *x)
82
83   Test if an object is the ``True`` singleton,
84   the same as ``x is True`` in Python.
85
86   .. versionadded:: 3.10
87
88
89.. c:function:: int Py_IsFalse(PyObject *x)
90
91   Test if an object is the ``False`` singleton,
92   the same as ``x is False`` in Python.
93
94   .. versionadded:: 3.10
95
96
97.. c:function:: PyTypeObject* Py_TYPE(PyObject *o)
98
99   Get the type of the Python object *o*.
100
101   Return a :term:`borrowed reference`.
102
103   Use the :c:func:`Py_SET_TYPE` function to set an object type.
104
105   .. versionchanged:: 3.11
106      :c:func:`Py_TYPE()` is changed to an inline static function.
107      The parameter type is no longer :c:expr:`const PyObject*`.
108
109
110.. c:function:: int Py_IS_TYPE(PyObject *o, PyTypeObject *type)
111
112   Return non-zero if the object *o* type is *type*. Return zero otherwise.
113   Equivalent to: ``Py_TYPE(o) == type``.
114
115   .. versionadded:: 3.9
116
117
118.. c:function:: void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
119
120   Set the object *o* type to *type*.
121
122   .. versionadded:: 3.9
123
124
125.. c:function:: Py_ssize_t Py_SIZE(PyVarObject *o)
126
127   Get the size of the Python object *o*.
128
129   Use the :c:func:`Py_SET_SIZE` function to set an object size.
130
131   .. versionchanged:: 3.11
132      :c:func:`Py_SIZE()` is changed to an inline static function.
133      The parameter type is no longer :c:expr:`const PyVarObject*`.
134
135
136.. c:function:: void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
137
138   Set the object *o* size to *size*.
139
140   .. versionadded:: 3.9
141
142
143.. c:macro:: PyObject_HEAD_INIT(type)
144
145   This is a macro which expands to initialization values for a new
146   :c:type:`PyObject` type.  This macro expands to::
147
148      _PyObject_EXTRA_INIT
149      1, type,
150
151
152.. c:macro:: PyVarObject_HEAD_INIT(type, size)
153
154   This is a macro which expands to initialization values for a new
155   :c:type:`PyVarObject` type, including the :c:member:`~PyVarObject.ob_size` field.
156   This macro expands to::
157
158      _PyObject_EXTRA_INIT
159      1, type, size,
160
161
162Implementing functions and methods
163----------------------------------
164
165.. c:type:: PyCFunction
166
167   Type of the functions used to implement most Python callables in C.
168   Functions of this type take two :c:expr:`PyObject*` parameters and return
169   one such value.  If the return value is ``NULL``, an exception shall have
170   been set.  If not ``NULL``, the return value is interpreted as the return
171   value of the function as exposed in Python.  The function must return a new
172   reference.
173
174   The function signature is::
175
176      PyObject *PyCFunction(PyObject *self,
177                            PyObject *args);
178
179.. c:type:: PyCFunctionWithKeywords
180
181   Type of the functions used to implement Python callables in C
182   with signature :ref:`METH_VARARGS | METH_KEYWORDS <METH_VARARGS-METH_KEYWORDS>`.
183   The function signature is::
184
185      PyObject *PyCFunctionWithKeywords(PyObject *self,
186                                        PyObject *args,
187                                        PyObject *kwargs);
188
189
190.. c:type:: PyCFunctionFast
191
192   Type of the functions used to implement Python callables in C
193   with signature :c:macro:`METH_FASTCALL`.
194   The function signature is::
195
196      PyObject *PyCFunctionFast(PyObject *self,
197                                PyObject *const *args,
198                                Py_ssize_t nargs);
199
200.. c:type:: PyCFunctionFastWithKeywords
201
202   Type of the functions used to implement Python callables in C
203   with signature :ref:`METH_FASTCALL | METH_KEYWORDS <METH_FASTCALL-METH_KEYWORDS>`.
204   The function signature is::
205
206      PyObject *PyCFunctionFastWithKeywords(PyObject *self,
207                                            PyObject *const *args,
208                                            Py_ssize_t nargs,
209                                            PyObject *kwnames);
210
211.. c:type:: PyCMethod
212
213   Type of the functions used to implement Python callables in C
214   with signature :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS <METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`.
215   The function signature is::
216
217      PyObject *PyCMethod(PyObject *self,
218                          PyTypeObject *defining_class,
219                          PyObject *const *args,
220                          Py_ssize_t nargs,
221                          PyObject *kwnames)
222
223   .. versionadded:: 3.9
224
225
226.. c:type:: PyMethodDef
227
228   Structure used to describe a method of an extension type.  This structure has
229   four fields:
230
231   .. c:member:: const char *ml_name
232
233      Name of the method.
234
235   .. c:member:: PyCFunction ml_meth
236
237      Pointer to the C implementation.
238
239   .. c:member:: int ml_flags
240
241      Flags bits indicating how the call should be constructed.
242
243   .. c:member:: const char *ml_doc
244
245      Points to the contents of the docstring.
246
247The :c:member:`~PyMethodDef.ml_meth` is a C function pointer.
248The functions may be of different
249types, but they always return :c:expr:`PyObject*`.  If the function is not of
250the :c:type:`PyCFunction`, the compiler will require a cast in the method table.
251Even though :c:type:`PyCFunction` defines the first parameter as
252:c:expr:`PyObject*`, it is common that the method implementation uses the
253specific C type of the *self* object.
254
255The :c:member:`~PyMethodDef.ml_flags` field is a bitfield which can include
256the following flags.
257The individual flags indicate either a calling convention or a binding
258convention.
259
260There are these calling conventions:
261
262.. c:macro:: METH_VARARGS
263
264   This is the typical calling convention, where the methods have the type
265   :c:type:`PyCFunction`. The function expects two :c:expr:`PyObject*` values.
266   The first one is the *self* object for methods; for module functions, it is
267   the module object.  The second parameter (often called *args*) is a tuple
268   object representing all arguments. This parameter is typically processed
269   using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`.
270
271
272.. c:macro:: METH_KEYWORDS
273
274   Can only be used in certain combinations with other flags:
275   :ref:`METH_VARARGS | METH_KEYWORDS <METH_VARARGS-METH_KEYWORDS>`,
276   :ref:`METH_FASTCALL | METH_KEYWORDS <METH_FASTCALL-METH_KEYWORDS>` and
277   :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS <METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`.
278
279
280.. _METH_VARARGS-METH_KEYWORDS:
281
282:c:expr:`METH_VARARGS | METH_KEYWORDS`
283   Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`.
284   The function expects three parameters: *self*, *args*, *kwargs* where
285   *kwargs* is a dictionary of all the keyword arguments or possibly ``NULL``
286   if there are no keyword arguments.  The parameters are typically processed
287   using :c:func:`PyArg_ParseTupleAndKeywords`.
288
289
290.. c:macro:: METH_FASTCALL
291
292   Fast calling convention supporting only positional arguments.
293   The methods have the type :c:type:`PyCFunctionFast`.
294   The first parameter is *self*, the second parameter is a C array
295   of :c:expr:`PyObject*` values indicating the arguments and the third
296   parameter is the number of arguments (the length of the array).
297
298   .. versionadded:: 3.7
299
300   .. versionchanged:: 3.10
301
302      ``METH_FASTCALL`` is now part of the :ref:`stable ABI <stable-abi>`.
303
304
305.. _METH_FASTCALL-METH_KEYWORDS:
306
307:c:expr:`METH_FASTCALL | METH_KEYWORDS`
308   Extension of :c:macro:`METH_FASTCALL` supporting also keyword arguments,
309   with methods of type :c:type:`PyCFunctionFastWithKeywords`.
310   Keyword arguments are passed the same way as in the
311   :ref:`vectorcall protocol <vectorcall>`:
312   there is an additional fourth :c:expr:`PyObject*` parameter
313   which is a tuple representing the names of the keyword arguments
314   (which are guaranteed to be strings)
315   or possibly ``NULL`` if there are no keywords.  The values of the keyword
316   arguments are stored in the *args* array, after the positional arguments.
317
318   .. versionadded:: 3.7
319
320
321.. c:macro:: METH_METHOD
322
323   Can only be used in the combination with other flags:
324   :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS <METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`.
325
326
327.. _METH_METHOD-METH_FASTCALL-METH_KEYWORDS:
328
329:c:expr:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS`
330   Extension of :ref:`METH_FASTCALL | METH_KEYWORDS <METH_FASTCALL-METH_KEYWORDS>`
331   supporting the *defining class*, that is,
332   the class that contains the method in question.
333   The defining class might be a superclass of ``Py_TYPE(self)``.
334
335   The method needs to be of type :c:type:`PyCMethod`, the same as for
336   ``METH_FASTCALL | METH_KEYWORDS`` with ``defining_class`` argument added after
337   ``self``.
338
339   .. versionadded:: 3.9
340
341
342.. c:macro:: METH_NOARGS
343
344   Methods without parameters don't need to check whether arguments are given if
345   they are listed with the :c:macro:`METH_NOARGS` flag.  They need to be of type
346   :c:type:`PyCFunction`.  The first parameter is typically named *self* and will
347   hold a reference to the module or object instance.  In all cases the second
348   parameter will be ``NULL``.
349
350   The function must have 2 parameters. Since the second parameter is unused,
351   :c:macro:`Py_UNUSED` can be used to prevent a compiler warning.
352
353
354.. c:macro:: METH_O
355
356   Methods with a single object argument can be listed with the :c:macro:`METH_O`
357   flag, instead of invoking :c:func:`PyArg_ParseTuple` with a ``"O"`` argument.
358   They have the type :c:type:`PyCFunction`, with the *self* parameter, and a
359   :c:expr:`PyObject*` parameter representing the single argument.
360
361
362These two constants are not used to indicate the calling convention but the
363binding when use with methods of classes.  These may not be used for functions
364defined for modules.  At most one of these flags may be set for any given
365method.
366
367
368.. c:macro:: METH_CLASS
369
370   .. index:: pair: built-in function; classmethod
371
372   The method will be passed the type object as the first parameter rather
373   than an instance of the type.  This is used to create *class methods*,
374   similar to what is created when using the :func:`classmethod` built-in
375   function.
376
377
378.. c:macro:: METH_STATIC
379
380   .. index:: pair: built-in function; staticmethod
381
382   The method will be passed ``NULL`` as the first parameter rather than an
383   instance of the type.  This is used to create *static methods*, similar to
384   what is created when using the :func:`staticmethod` built-in function.
385
386One other constant controls whether a method is loaded in place of another
387definition with the same method name.
388
389
390.. c:macro:: METH_COEXIST
391
392   The method will be loaded in place of existing definitions.  Without
393   *METH_COEXIST*, the default is to skip repeated definitions.  Since slot
394   wrappers are loaded before the method table, the existence of a
395   *sq_contains* slot, for example, would generate a wrapped method named
396   :meth:`~object.__contains__` and preclude the loading of a corresponding
397   PyCFunction with the same name.  With the flag defined, the PyCFunction
398   will be loaded in place of the wrapper object and will co-exist with the
399   slot.  This is helpful because calls to PyCFunctions are optimized more
400   than wrapper object calls.
401
402.. c:function:: PyObject * PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
403
404   Turn *ml* into a Python :term:`callable` object.
405   The caller must ensure that *ml* outlives the :term:`callable`.
406   Typically, *ml* is defined as a static variable.
407
408   The *self* parameter will be passed as the *self* argument
409   to the C function in ``ml->ml_meth`` when invoked.
410   *self* can be ``NULL``.
411
412   The :term:`callable` object's ``__module__`` attribute
413   can be set from the given *module* argument.
414   *module* should be a Python string,
415   which will be used as name of the module the function is defined in.
416   If unavailable, it can be set to :const:`None` or ``NULL``.
417
418   .. seealso:: :attr:`function.__module__`
419
420   The *cls* parameter will be passed as the *defining_class*
421   argument to the C function.
422   Must be set if :c:macro:`METH_METHOD` is set on ``ml->ml_flags``.
423
424   .. versionadded:: 3.9
425
426
427.. c:function:: PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
428
429   Equivalent to ``PyCMethod_New(ml, self, module, NULL)``.
430
431
432.. c:function:: PyObject * PyCFunction_New(PyMethodDef *ml, PyObject *self)
433
434   Equivalent to ``PyCMethod_New(ml, self, NULL, NULL)``.
435
436
437Accessing attributes of extension types
438---------------------------------------
439
440.. c:type:: PyMemberDef
441
442   Structure which describes an attribute of a type which corresponds to a C
443   struct member.
444   When defining a class, put a NULL-terminated array of these
445   structures in the :c:member:`~PyTypeObject.tp_members` slot.
446
447   Its fields are, in order:
448
449   .. c:member:: const char* name
450
451         Name of the member.
452         A NULL value marks the end of a ``PyMemberDef[]`` array.
453
454         The string should be static, no copy is made of it.
455
456   .. c:member:: int type
457
458      The type of the member in the C struct.
459      See :ref:`PyMemberDef-types` for the possible values.
460
461   .. c:member:: Py_ssize_t offset
462
463      The offset in bytes that the member is located on the type’s object struct.
464
465   .. c:member:: int flags
466
467      Zero or more of the :ref:`PyMemberDef-flags`, combined using bitwise OR.
468
469   .. c:member:: const char* doc
470
471      The docstring, or NULL.
472      The string should be static, no copy is made of it.
473      Typically, it is defined using :c:macro:`PyDoc_STR`.
474
475   By default (when :c:member:`~PyMemberDef.flags` is ``0``), members allow
476   both read and write access.
477   Use the :c:macro:`Py_READONLY` flag for read-only access.
478   Certain types, like :c:macro:`Py_T_STRING`, imply :c:macro:`Py_READONLY`.
479   Only :c:macro:`Py_T_OBJECT_EX` (and legacy :c:macro:`T_OBJECT`) members can
480   be deleted.
481
482   .. _pymemberdef-offsets:
483
484   For heap-allocated types (created using :c:func:`PyType_FromSpec` or similar),
485   ``PyMemberDef`` may contain a definition for the special member
486   ``"__vectorcalloffset__"``, corresponding to
487   :c:member:`~PyTypeObject.tp_vectorcall_offset` in type objects.
488   These must be defined with ``Py_T_PYSSIZET`` and ``Py_READONLY``, for example::
489
490      static PyMemberDef spam_type_members[] = {
491          {"__vectorcalloffset__", Py_T_PYSSIZET,
492           offsetof(Spam_object, vectorcall), Py_READONLY},
493          {NULL}  /* Sentinel */
494      };
495
496   (You may need to ``#include <stddef.h>`` for :c:func:`!offsetof`.)
497
498   The legacy offsets :c:member:`~PyTypeObject.tp_dictoffset` and
499   :c:member:`~PyTypeObject.tp_weaklistoffset` can be defined similarly using
500   ``"__dictoffset__"`` and ``"__weaklistoffset__"`` members, but extensions
501   are strongly encouraged to use :c:macro:`Py_TPFLAGS_MANAGED_DICT` and
502   :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` instead.
503
504   .. versionchanged:: 3.12
505
506      ``PyMemberDef`` is always available.
507      Previously, it required including ``"structmember.h"``.
508
509.. c:function:: PyObject* PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)
510
511   Get an attribute belonging to the object at address *obj_addr*.  The
512   attribute is described by ``PyMemberDef`` *m*.  Returns ``NULL``
513   on error.
514
515   .. versionchanged:: 3.12
516
517      ``PyMember_GetOne`` is always available.
518      Previously, it required including ``"structmember.h"``.
519
520.. c:function:: int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)
521
522   Set an attribute belonging to the object at address *obj_addr* to object *o*.
523   The attribute to set is described by ``PyMemberDef`` *m*.  Returns ``0``
524   if successful and a negative value on failure.
525
526   .. versionchanged:: 3.12
527
528      ``PyMember_SetOne`` is always available.
529      Previously, it required including ``"structmember.h"``.
530
531.. _PyMemberDef-flags:
532
533Member flags
534^^^^^^^^^^^^
535
536The following flags can be used with :c:member:`PyMemberDef.flags`:
537
538.. c:macro:: Py_READONLY
539
540   Not writable.
541
542.. c:macro:: Py_AUDIT_READ
543
544   Emit an ``object.__getattr__`` :ref:`audit event <audit-events>`
545   before reading.
546
547.. c:macro:: Py_RELATIVE_OFFSET
548
549   Indicates that the :c:member:`~PyMemberDef.offset` of this ``PyMemberDef``
550   entry indicates an offset from the subclass-specific data, rather than
551   from ``PyObject``.
552
553   Can only be used as part of :c:member:`Py_tp_members <PyTypeObject.tp_members>`
554   :c:type:`slot <PyType_Slot>` when creating a class using negative
555   :c:member:`~PyType_Spec.basicsize`.
556   It is mandatory in that case.
557
558   This flag is only used in :c:type:`PyType_Slot`.
559   When setting :c:member:`~PyTypeObject.tp_members` during
560   class creation, Python clears it and sets
561   :c:member:`PyMemberDef.offset` to the offset from the ``PyObject`` struct.
562
563.. index::
564   single: READ_RESTRICTED (C macro)
565   single: WRITE_RESTRICTED (C macro)
566   single: RESTRICTED (C macro)
567
568.. versionchanged:: 3.10
569
570   The :c:macro:`!RESTRICTED`, :c:macro:`!READ_RESTRICTED` and
571   :c:macro:`!WRITE_RESTRICTED` macros available with
572   ``#include "structmember.h"`` are deprecated.
573   :c:macro:`!READ_RESTRICTED` and :c:macro:`!RESTRICTED` are equivalent to
574   :c:macro:`Py_AUDIT_READ`; :c:macro:`!WRITE_RESTRICTED` does nothing.
575
576.. index::
577   single: READONLY (C macro)
578
579.. versionchanged:: 3.12
580
581   The :c:macro:`!READONLY` macro was renamed to :c:macro:`Py_READONLY`.
582   The :c:macro:`!PY_AUDIT_READ` macro was renamed with the ``Py_`` prefix.
583   The new names are now always available.
584   Previously, these required ``#include "structmember.h"``.
585   The header is still available and it provides the old names.
586
587.. _PyMemberDef-types:
588
589Member types
590^^^^^^^^^^^^
591
592:c:member:`PyMemberDef.type` can be one of the following macros corresponding
593to various C types.
594When the member is accessed in Python, it will be converted to the
595equivalent Python type.
596When it is set from Python, it will be converted back to the C type.
597If that is not possible, an exception such as :exc:`TypeError` or
598:exc:`ValueError` is raised.
599
600Unless marked (D), attributes defined this way cannot be deleted
601using e.g. :keyword:`del` or :py:func:`delattr`.
602
603================================ ============================= ======================
604Macro name                       C type                        Python type
605================================ ============================= ======================
606.. c:macro:: Py_T_BYTE           :c:expr:`char`                :py:class:`int`
607.. c:macro:: Py_T_SHORT          :c:expr:`short`               :py:class:`int`
608.. c:macro:: Py_T_INT            :c:expr:`int`                 :py:class:`int`
609.. c:macro:: Py_T_LONG           :c:expr:`long`                :py:class:`int`
610.. c:macro:: Py_T_LONGLONG       :c:expr:`long long`           :py:class:`int`
611.. c:macro:: Py_T_UBYTE          :c:expr:`unsigned char`       :py:class:`int`
612.. c:macro:: Py_T_UINT           :c:expr:`unsigned int`        :py:class:`int`
613.. c:macro:: Py_T_USHORT         :c:expr:`unsigned short`      :py:class:`int`
614.. c:macro:: Py_T_ULONG          :c:expr:`unsigned long`       :py:class:`int`
615.. c:macro:: Py_T_ULONGLONG      :c:expr:`unsigned long long`  :py:class:`int`
616.. c:macro:: Py_T_PYSSIZET       :c:expr:`Py_ssize_t`          :py:class:`int`
617.. c:macro:: Py_T_FLOAT          :c:expr:`float`               :py:class:`float`
618.. c:macro:: Py_T_DOUBLE         :c:expr:`double`              :py:class:`float`
619.. c:macro:: Py_T_BOOL           :c:expr:`char`                :py:class:`bool`
620                                 (written as 0 or 1)
621.. c:macro:: Py_T_STRING         :c:expr:`const char *` (*)    :py:class:`str` (RO)
622.. c:macro:: Py_T_STRING_INPLACE :c:expr:`const char[]` (*)    :py:class:`str` (RO)
623.. c:macro:: Py_T_CHAR           :c:expr:`char` (0-127)        :py:class:`str` (**)
624.. c:macro:: Py_T_OBJECT_EX      :c:expr:`PyObject *`          :py:class:`object` (D)
625================================ ============================= ======================
626
627   (*): Zero-terminated, UTF8-encoded C string.
628   With :c:macro:`!Py_T_STRING` the C representation is a pointer;
629   with :c:macro:`!Py_T_STRING_INPLACE` the string is stored directly
630   in the structure.
631
632   (**): String of length 1. Only ASCII is accepted.
633
634   (RO): Implies :c:macro:`Py_READONLY`.
635
636   (D): Can be deleted, in which case the pointer is set to ``NULL``.
637   Reading a ``NULL`` pointer raises :py:exc:`AttributeError`.
638
639.. index::
640   single: T_BYTE (C macro)
641   single: T_SHORT (C macro)
642   single: T_INT (C macro)
643   single: T_LONG (C macro)
644   single: T_LONGLONG (C macro)
645   single: T_UBYTE (C macro)
646   single: T_USHORT (C macro)
647   single: T_UINT (C macro)
648   single: T_ULONG (C macro)
649   single: T_ULONGULONG (C macro)
650   single: T_PYSSIZET (C macro)
651   single: T_FLOAT (C macro)
652   single: T_DOUBLE (C macro)
653   single: T_BOOL (C macro)
654   single: T_CHAR (C macro)
655   single: T_STRING (C macro)
656   single: T_STRING_INPLACE (C macro)
657   single: T_OBJECT_EX (C macro)
658   single: structmember.h
659
660.. versionadded:: 3.12
661
662   In previous versions, the macros were only available with
663   ``#include "structmember.h"`` and were named without the ``Py_`` prefix
664   (e.g. as ``T_INT``).
665   The header is still available and contains the old names, along with
666   the following deprecated types:
667
668   .. c:macro:: T_OBJECT
669
670      Like ``Py_T_OBJECT_EX``, but ``NULL`` is converted to ``None``.
671      This results in surprising behavior in Python: deleting the attribute
672      effectively sets it to ``None``.
673
674   .. c:macro:: T_NONE
675
676      Always ``None``. Must be used with :c:macro:`Py_READONLY`.
677
678Defining Getters and Setters
679^^^^^^^^^^^^^^^^^^^^^^^^^^^^
680
681.. c:type:: PyGetSetDef
682
683   Structure to define property-like access for a type. See also description of
684   the :c:member:`PyTypeObject.tp_getset` slot.
685
686   .. c:member:: const char* name
687
688      attribute name
689
690   .. c:member:: getter get
691
692      C function to get the attribute.
693
694   .. c:member:: setter set
695
696      Optional C function to set or delete the attribute.
697      If ``NULL``, the attribute is read-only.
698
699   .. c:member:: const char* doc
700
701      optional docstring
702
703   .. c:member:: void* closure
704
705      Optional user data pointer, providing additional data for getter and setter.
706
707.. c:type:: PyObject *(*getter)(PyObject *, void *)
708
709   The ``get`` function takes one :c:expr:`PyObject*` parameter (the
710   instance) and a user data pointer (the associated ``closure``):
711
712   It should return a new reference on success or ``NULL`` with a set exception
713   on failure.
714
715.. c:type:: int (*setter)(PyObject *, PyObject *, void *)
716
717   ``set`` functions take two :c:expr:`PyObject*` parameters (the instance and
718   the value to be set) and a user data pointer (the associated ``closure``):
719
720   In case the attribute should be deleted the second parameter is ``NULL``.
721   Should return ``0`` on success or ``-1`` with a set exception on failure.
722