Debian Codegraph @

Doc/c-api/structures.rst

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