]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/python/contrib/Doc/c-api/structures.rst
Inital import
[l4.git] / l4 / pkg / python / contrib / Doc / c-api / structures.rst
1 .. highlightlang:: 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 All Python objects ultimately share a small number of fields at the beginning
13 of the object's representation in memory.  These are represented by the
14 :ctype:`PyObject` and :ctype:`PyVarObject` types, which are defined, in turn,
15 by the expansions of some macros also used, whether directly or indirectly, in
16 the definition of all other Python objects.
17
18
19 .. ctype:: PyObject
20
21    All object types are extensions of this type.  This is a type which
22    contains the information Python needs to treat a pointer to an object as an
23    object.  In a normal "release" build, it contains only the object's
24    reference count and a pointer to the corresponding type object.  It
25    corresponds to the fields defined by the expansion of the ``PyObject_HEAD``
26    macro.
27
28
29 .. ctype:: PyVarObject
30
31    This is an extension of :ctype:`PyObject` that adds the :attr:`ob_size`
32    field.  This is only used for objects that have some notion of *length*.
33    This type does not often appear in the Python/C API.  It corresponds to the
34    fields defined by the expansion of the ``PyObject_VAR_HEAD`` macro.
35
36 These macros are used in the definition of :ctype:`PyObject` and
37 :ctype:`PyVarObject`:
38
39
40 .. cmacro:: PyObject_HEAD
41
42    This is a macro which expands to the declarations of the fields of the
43    :ctype:`PyObject` type; it is used when declaring new types which represent
44    objects without a varying length.  The specific fields it expands to depend
45    on the definition of :cmacro:`Py_TRACE_REFS`.  By default, that macro is
46    not defined, and :cmacro:`PyObject_HEAD` expands to::
47
48       Py_ssize_t ob_refcnt;
49       PyTypeObject *ob_type;
50
51    When :cmacro:`Py_TRACE_REFS` is defined, it expands to::
52
53       PyObject *_ob_next, *_ob_prev;
54       Py_ssize_t ob_refcnt;
55       PyTypeObject *ob_type;
56
57
58 .. cmacro:: PyObject_VAR_HEAD
59
60    This is a macro which expands to the declarations of the fields of the
61    :ctype:`PyVarObject` type; it is used when declaring new types which
62    represent objects with a length that varies from instance to instance.
63    This macro always expands to::
64
65       PyObject_HEAD
66       Py_ssize_t ob_size;
67
68    Note that :cmacro:`PyObject_HEAD` is part of the expansion, and that its own
69    expansion varies depending on the definition of :cmacro:`Py_TRACE_REFS`.
70
71
72 .. cmacro:: PyObject_HEAD_INIT(type)
73
74    This is a macro which expands to initialization values for a new
75    :ctype:`PyObject` type.  This macro expands to::
76
77       _PyObject_EXTRA_INIT
78       1, type,
79
80
81 .. cmacro:: PyVarObject_HEAD_INIT(type, size)
82
83    This is a macro which expands to initialization values for a new
84    :ctype:`PyVarObject` type, including the :attr:`ob_size` field.
85    This macro expands to::
86
87       _PyObject_EXTRA_INIT
88       1, type, size,
89
90
91 .. ctype:: PyCFunction
92
93    Type of the functions used to implement most Python callables in C.
94    Functions of this type take two :ctype:`PyObject\*` parameters and return
95    one such value.  If the return value is *NULL*, an exception shall have
96    been set.  If not *NULL*, the return value is interpreted as the return
97    value of the function as exposed in Python.  The function must return a new
98    reference.
99
100
101 .. ctype:: PyMethodDef
102
103    Structure used to describe a method of an extension type.  This structure has
104    four fields:
105
106    +------------------+-------------+-------------------------------+
107    | Field            | C Type      | Meaning                       |
108    +==================+=============+===============================+
109    | :attr:`ml_name`  | char \*     | name of the method            |
110    +------------------+-------------+-------------------------------+
111    | :attr:`ml_meth`  | PyCFunction | pointer to the C              |
112    |                  |             | implementation                |
113    +------------------+-------------+-------------------------------+
114    | :attr:`ml_flags` | int         | flag bits indicating how the  |
115    |                  |             | call should be constructed    |
116    +------------------+-------------+-------------------------------+
117    | :attr:`ml_doc`   | char \*     | points to the contents of the |
118    |                  |             | docstring                     |
119    +------------------+-------------+-------------------------------+
120
121 The :attr:`ml_meth` is a C function pointer.  The functions may be of different
122 types, but they always return :ctype:`PyObject\*`.  If the function is not of
123 the :ctype:`PyCFunction`, the compiler will require a cast in the method table.
124 Even though :ctype:`PyCFunction` defines the first parameter as
125 :ctype:`PyObject\*`, it is common that the method implementation uses a the
126 specific C type of the *self* object.
127
128 The :attr:`ml_flags` field is a bitfield which can include the following flags.
129 The individual flags indicate either a calling convention or a binding
130 convention.  Of the calling convention flags, only :const:`METH_VARARGS` and
131 :const:`METH_KEYWORDS` can be combined (but note that :const:`METH_KEYWORDS`
132 alone is equivalent to ``METH_VARARGS | METH_KEYWORDS``). Any of the calling
133 convention flags can be combined with a binding flag.
134
135
136 .. data:: METH_VARARGS
137
138    This is the typical calling convention, where the methods have the type
139    :ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values.
140    The first one is the *self* object for methods; for module functions, it
141    has the value given to :cfunc:`Py_InitModule4` (or *NULL* if
142    :cfunc:`Py_InitModule` was used).  The second parameter (often called
143    *args*) is a tuple object representing all arguments. This parameter is
144    typically processed using :cfunc:`PyArg_ParseTuple` or
145    :cfunc:`PyArg_UnpackTuple`.
146
147
148 .. data:: METH_KEYWORDS
149
150    Methods with these flags must be of type :ctype:`PyCFunctionWithKeywords`.
151    The function expects three parameters: *self*, *args*, and a dictionary of
152    all the keyword arguments.  The flag is typically combined with
153    :const:`METH_VARARGS`, and the parameters are typically processed using
154    :cfunc:`PyArg_ParseTupleAndKeywords`.
155
156
157 .. data:: METH_NOARGS
158
159    Methods without parameters don't need to check whether arguments are given if
160    they are listed with the :const:`METH_NOARGS` flag.  They need to be of type
161    :ctype:`PyCFunction`.  When used with object methods, the first parameter is
162    typically named ``self`` and will hold a reference to the object instance.
163    In all cases the second parameter will be *NULL*.
164
165
166 .. data:: METH_O
167
168    Methods with a single object argument can be listed with the :const:`METH_O`
169    flag, instead of invoking :cfunc:`PyArg_ParseTuple` with a ``"O"`` argument.
170    They have the type :ctype:`PyCFunction`, with the *self* parameter, and a
171    :ctype:`PyObject\*` parameter representing the single argument.
172
173
174 .. data:: METH_OLDARGS
175
176    This calling convention is deprecated.  The method must be of type
177    :ctype:`PyCFunction`.  The second argument is *NULL* if no arguments are
178    given, a single object if exactly one argument is given, and a tuple of
179    objects if more than one argument is given.  There is no way for a function
180    using this convention to distinguish between a call with multiple arguments
181    and a call with a tuple as the only argument.
182
183 These two constants are not used to indicate the calling convention but the
184 binding when use with methods of classes.  These may not be used for functions
185 defined for modules.  At most one of these flags may be set for any given
186 method.
187
188
189 .. data:: METH_CLASS
190
191    .. index:: builtin: classmethod
192
193    The method will be passed the type object as the first parameter rather
194    than an instance of the type.  This is used to create *class methods*,
195    similar to what is created when using the :func:`classmethod` built-in
196    function.
197
198    .. versionadded:: 2.3
199
200
201 .. data:: METH_STATIC
202
203    .. index:: builtin: staticmethod
204
205    The method will be passed *NULL* as the first parameter rather than an
206    instance of the type.  This is used to create *static methods*, similar to
207    what is created when using the :func:`staticmethod` built-in function.
208
209    .. versionadded:: 2.3
210
211 One other constant controls whether a method is loaded in place of another
212 definition with the same method name.
213
214
215 .. data:: METH_COEXIST
216
217    The method will be loaded in place of existing definitions.  Without
218    *METH_COEXIST*, the default is to skip repeated definitions.  Since slot
219    wrappers are loaded before the method table, the existence of a
220    *sq_contains* slot, for example, would generate a wrapped method named
221    :meth:`__contains__` and preclude the loading of a corresponding
222    PyCFunction with the same name.  With the flag defined, the PyCFunction
223    will be loaded in place of the wrapper object and will co-exist with the
224    slot.  This is helpful because calls to PyCFunctions are optimized more
225    than wrapper object calls.
226
227    .. versionadded:: 2.4
228
229
230 .. ctype:: PyMemberDef
231
232    Structure which describes an attribute of a type which corresponds to a C
233    struct member.  Its fields are:
234
235    +------------------+-------------+-------------------------------+
236    | Field            | C Type      | Meaning                       |
237    +==================+=============+===============================+
238    | :attr:`name`     | char \*     | name of the member            |
239    +------------------+-------------+-------------------------------+
240    | :attr:`type`     | int         | the type of the member in the |
241    |                  |             | C struct                      |
242    +------------------+-------------+-------------------------------+
243    | :attr:`offset`   | Py_ssize_t  | the offset in bytes that the  |
244    |                  |             | member is located on the      |
245    |                  |             | type's object struct          |
246    +------------------+-------------+-------------------------------+
247    | :attr:`flags`    | int         | flag bits indicating if the   |
248    |                  |             | field should be read-only or  |
249    |                  |             | writable                      |
250    +------------------+-------------+-------------------------------+
251    | :attr:`doc`      | char \*     | points to the contents of the |
252    |                  |             | docstring                     |
253    +------------------+-------------+-------------------------------+
254
255    :attr:`type` can be one of many ``T_`` macros corresponding to various C
256    types.  When the member is accessed in Python, it will be converted to the
257    equivalent Python type.
258
259    =============== ==================
260    Macro name      C type
261    =============== ==================
262    T_SHORT         short
263    T_INT           int
264    T_LONG          long
265    T_FLOAT         float
266    T_DOUBLE        double
267    T_STRING        char \*
268    T_OBJECT        PyObject \*
269    T_OBJECT_EX     PyObject \*
270    T_CHAR          char
271    T_BYTE          char
272    T_UBYTE         unsigned char
273    T_UINT          unsigned int
274    T_USHORT        unsigned short
275    T_ULONG         unsigned long
276    T_BOOL          char
277    T_LONGLONG      long long
278    T_ULONGLONG     unsigned long long
279    T_PYSSIZET      Py_ssize_t
280    =============== ==================
281
282    :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that
283    :cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and
284    :cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`.
285
286    :attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for
287    read-only access.  Using :cmacro:`T_STRING` for :attr:`type` implies
288    :cmacro:`READONLY`.  Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX`
289    members can be deleted.  (They are set to *NULL*).
290
291
292 .. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)
293
294    Return a bound method object for an extension type implemented in C.  This
295    can be useful in the implementation of a :attr:`tp_getattro` or
296    :attr:`tp_getattr` handler that does not use the
297    :cfunc:`PyObject_GenericGetAttr` function.