Debian Codegraph @

Doc/c-api/arg.rst

raw
1 .. highlight:: c
2
3 .. _arg-parsing:
4
5 Parsing arguments and building values
6 =====================================
7
8 These functions are useful when creating your own extension functions and
9 methods. Additional information and examples are available in
10 :ref:`extending-index`.
11
12 The first three of these functions described, :c:func:`PyArg_ParseTuple`,
13 :c:func:`PyArg_ParseTupleAndKeywords`, and :c:func:`PyArg_Parse`, all use *format
14 strings* which are used to tell the function about the expected arguments. The
15 format strings use the same syntax for each of these functions.
16
17 -----------------
18 Parsing arguments
19 -----------------
20
21 A format string consists of zero or more "format units." A format unit
22 describes one Python object; it is usually a single character or a parenthesized
23 sequence of format units. With a few exceptions, a format unit that is not a
24 parenthesized sequence normally corresponds to a single address argument to
25 these functions. In the following description, the quoted form is the format
26 unit; the entry in (round) parentheses is the Python object type that matches
27 the format unit; and the entry in [square] brackets is the type of the C
28 variable(s) whose address should be passed.
29
30 .. _arg-parsing-string-and-buffers:
31
32 Strings and buffers
33 -------------------
34
35 .. note::
36
37 On Python 3.12 and older, the macro :c:macro:`!PY_SSIZE_T_CLEAN` must be
38 defined before including :file:`Python.h` to use all ``#`` variants of
39 formats (``s#``, ``y#``, etc.) explained below.
40 This is not necessary on Python 3.13 and later.
41
42 These formats allow accessing an object as a contiguous chunk of memory.
43 You don't have to provide raw storage for the returned unicode or bytes
44 area.
45
46 Unless otherwise stated, buffers are not NUL-terminated.
47
48 There are three ways strings and buffers can be converted to C:
49
50 * Formats such as ``y*`` and ``s*`` fill a :c:type:`Py_buffer` structure.
51 This locks the underlying buffer so that the caller can subsequently use
52 the buffer even inside a :c:type:`Py_BEGIN_ALLOW_THREADS`
53 block without the risk of mutable data being resized or destroyed.
54 As a result, **you have to call** :c:func:`PyBuffer_Release` after you have
55 finished processing the data (or in any early abort case).
56
57 * The ``es``, ``es#``, ``et`` and ``et#`` formats allocate the result buffer.
58 **You have to call** :c:func:`PyMem_Free` after you have finished
59 processing the data (or in any early abort case).
60
61 * .. _c-arg-borrowed-buffer:
62
63 Other formats take a :class:`str` or a read-only :term:`bytes-like object`,
64 such as :class:`bytes`, and provide a ``const char *`` pointer to
65 its buffer.
66 In this case the buffer is "borrowed": it is managed by the corresponding
67 Python object, and shares the lifetime of this object.
68 You won't have to release any memory yourself.
69
70 To ensure that the underlying buffer may be safely borrowed, the object's
71 :c:member:`PyBufferProcs.bf_releasebuffer` field must be ``NULL``.
72 This disallows common mutable objects such as :class:`bytearray`,
73 but also some read-only objects such as :class:`memoryview` of
74 :class:`bytes`.
75
76 Besides this ``bf_releasebuffer`` requirement, there is no check to verify
77 whether the input object is immutable (e.g. whether it would honor a request
78 for a writable buffer, or whether another thread can mutate the data).
79
80 ``s`` (:class:`str`) [const char \*]
81 Convert a Unicode object to a C pointer to a character string.
82 A pointer to an existing string is stored in the character pointer
83 variable whose address you pass. The C string is NUL-terminated.
84 The Python string must not contain embedded null code points; if it does,
85 a :exc:`ValueError` exception is raised. Unicode objects are converted
86 to C strings using ``'utf-8'`` encoding. If this conversion fails, a
87 :exc:`UnicodeError` is raised.
88
89 .. note::
90 This format does not accept :term:`bytes-like objects
91 <bytes-like object>`. If you want to accept
92 filesystem paths and convert them to C character strings, it is
93 preferable to use the ``O&`` format with :c:func:`PyUnicode_FSConverter`
94 as *converter*.
95
96 .. versionchanged:: 3.5
97 Previously, :exc:`TypeError` was raised when embedded null code points
98 were encountered in the Python string.
99
100 ``s*`` (:class:`str` or :term:`bytes-like object`) [Py_buffer]
101 This format accepts Unicode objects as well as bytes-like objects.
102 It fills a :c:type:`Py_buffer` structure provided by the caller.
103 In this case the resulting C string may contain embedded NUL bytes.
104 Unicode objects are converted to C strings using ``'utf-8'`` encoding.
105
106 ``s#`` (:class:`str`, read-only :term:`bytes-like object`) [const char \*, :c:type:`Py_ssize_t`]
107 Like ``s*``, except that it provides a :ref:`borrowed buffer <c-arg-borrowed-buffer>`.
108 The result is stored into two C variables,
109 the first one a pointer to a C string, the second one its length.
110 The string may contain embedded null bytes. Unicode objects are converted
111 to C strings using ``'utf-8'`` encoding.
112
113 ``z`` (:class:`str` or ``None``) [const char \*]
114 Like ``s``, but the Python object may also be ``None``, in which case the C
115 pointer is set to ``NULL``.
116
117 ``z*`` (:class:`str`, :term:`bytes-like object` or ``None``) [Py_buffer]
118 Like ``s*``, but the Python object may also be ``None``, in which case the
119 ``buf`` member of the :c:type:`Py_buffer` structure is set to ``NULL``.
120
121 ``z#`` (:class:`str`, read-only :term:`bytes-like object` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
122 Like ``s#``, but the Python object may also be ``None``, in which case the C
123 pointer is set to ``NULL``.
124
125 ``y`` (read-only :term:`bytes-like object`) [const char \*]
126 This format converts a bytes-like object to a C pointer to a
127 :ref:`borrowed <c-arg-borrowed-buffer>` character string;
128 it does not accept Unicode objects. The bytes buffer must not
129 contain embedded null bytes; if it does, a :exc:`ValueError`
130 exception is raised.
131
132 .. versionchanged:: 3.5
133 Previously, :exc:`TypeError` was raised when embedded null bytes were
134 encountered in the bytes buffer.
135
136 ``y*`` (:term:`bytes-like object`) [Py_buffer]
137 This variant on ``s*`` doesn't accept Unicode objects, only
138 bytes-like objects. **This is the recommended way to accept
139 binary data.**
140
141 ``y#`` (read-only :term:`bytes-like object`) [const char \*, :c:type:`Py_ssize_t`]
142 This variant on ``s#`` doesn't accept Unicode objects, only bytes-like
143 objects.
144
145 ``S`` (:class:`bytes`) [PyBytesObject \*]
146 Requires that the Python object is a :class:`bytes` object, without
147 attempting any conversion. Raises :exc:`TypeError` if the object is not
148 a bytes object. The C variable may also be declared as :c:expr:`PyObject*`.
149
150 ``Y`` (:class:`bytearray`) [PyByteArrayObject \*]
151 Requires that the Python object is a :class:`bytearray` object, without
152 attempting any conversion. Raises :exc:`TypeError` if the object is not
153 a :class:`bytearray` object. The C variable may also be declared as :c:expr:`PyObject*`.
154
155 ``U`` (:class:`str`) [PyObject \*]
156 Requires that the Python object is a Unicode object, without attempting
157 any conversion. Raises :exc:`TypeError` if the object is not a Unicode
158 object. The C variable may also be declared as :c:expr:`PyObject*`.
159
160 ``w*`` (read-write :term:`bytes-like object`) [Py_buffer]
161 This format accepts any object which implements the read-write buffer
162 interface. It fills a :c:type:`Py_buffer` structure provided by the caller.
163 The buffer may contain embedded null bytes. The caller has to call
164 :c:func:`PyBuffer_Release` when it is done with the buffer.
165
166 ``es`` (:class:`str`) [const char \*encoding, char \*\*buffer]
167 This variant on ``s`` is used for encoding Unicode into a character buffer.
168 It only works for encoded data without embedded NUL bytes.
169
170 This format requires two arguments. The first is only used as input, and
171 must be a :c:expr:`const char*` which points to the name of an encoding as a
172 NUL-terminated string, or ``NULL``, in which case ``'utf-8'`` encoding is used.
173 An exception is raised if the named encoding is not known to Python. The
174 second argument must be a :c:expr:`char**`; the value of the pointer it
175 references will be set to a buffer with the contents of the argument text.
176 The text will be encoded in the encoding specified by the first argument.
177
178 :c:func:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the
179 encoded data into this buffer and adjust *\*buffer* to reference the newly
180 allocated storage. The caller is responsible for calling :c:func:`PyMem_Free` to
181 free the allocated buffer after use.
182
183 ``et`` (:class:`str`, :class:`bytes` or :class:`bytearray`) [const char \*encoding, char \*\*buffer]
184 Same as ``es`` except that byte string objects are passed through without
185 recoding them. Instead, the implementation assumes that the byte string object uses
186 the encoding passed in as parameter.
187
188 ``es#`` (:class:`str`) [const char \*encoding, char \*\*buffer, :c:type:`Py_ssize_t` \*buffer_length]
189 This variant on ``s#`` is used for encoding Unicode into a character buffer.
190 Unlike the ``es`` format, this variant allows input data which contains NUL
191 characters.
192
193 It requires three arguments. The first is only used as input, and must be a
194 :c:expr:`const char*` which points to the name of an encoding as a
195 NUL-terminated string, or ``NULL``, in which case ``'utf-8'`` encoding is used.
196 An exception is raised if the named encoding is not known to Python. The
197 second argument must be a :c:expr:`char**`; the value of the pointer it
198 references will be set to a buffer with the contents of the argument text.
199 The text will be encoded in the encoding specified by the first argument.
200 The third argument must be a pointer to an integer; the referenced integer
201 will be set to the number of bytes in the output buffer.
202
203 There are two modes of operation:
204
205 If *\*buffer* points a ``NULL`` pointer, the function will allocate a buffer of
206 the needed size, copy the encoded data into this buffer and set *\*buffer* to
207 reference the newly allocated storage. The caller is responsible for calling
208 :c:func:`PyMem_Free` to free the allocated buffer after usage.
209
210 If *\*buffer* points to a non-``NULL`` pointer (an already allocated buffer),
211 :c:func:`PyArg_ParseTuple` will use this location as the buffer and interpret the
212 initial value of *\*buffer_length* as the buffer size. It will then copy the
213 encoded data into the buffer and NUL-terminate it. If the buffer is not large
214 enough, a :exc:`ValueError` will be set.
215
216 In both cases, *\*buffer_length* is set to the length of the encoded data
217 without the trailing NUL byte.
218
219 ``et#`` (:class:`str`, :class:`bytes` or :class:`bytearray`) [const char \*encoding, char \*\*buffer, :c:type:`Py_ssize_t` \*buffer_length]
220 Same as ``es#`` except that byte string objects are passed through without recoding
221 them. Instead, the implementation assumes that the byte string object uses the
222 encoding passed in as parameter.
223
224 .. versionchanged:: 3.12
225 ``u``, ``u#``, ``Z``, and ``Z#`` are removed because they used a legacy
226 ``Py_UNICODE*`` representation.
227
228
229 Numbers
230 -------
231
232 These formats allow representing Python numbers or single characters as C numbers.
233 Formats that require :class:`int`, :class:`float` or :class:`complex` can
234 also use the corresponding special methods :meth:`~object.__index__`,
235 :meth:`~object.__float__` or :meth:`~object.__complex__` to convert
236 the Python object to the required type.
237
238 For signed integer formats, :exc:`OverflowError` is raised if the value
239 is out of range for the C type.
240 For unsigned integer formats, no range checking is done --- the
241 most significant bits are silently truncated when the receiving field is too
242 small to receive the value.
243
244 ``b`` (:class:`int`) [unsigned char]
245 Convert a nonnegative Python integer to an unsigned tiny integer, stored in a C
246 :c:expr:`unsigned char`.
247
248 ``B`` (:class:`int`) [unsigned char]
249 Convert a Python integer to a tiny integer without overflow checking, stored in a C
250 :c:expr:`unsigned char`.
251
252 ``h`` (:class:`int`) [short int]
253 Convert a Python integer to a C :c:expr:`short int`.
254
255 ``H`` (:class:`int`) [unsigned short int]
256 Convert a Python integer to a C :c:expr:`unsigned short int`, without overflow
257 checking.
258
259 ``i`` (:class:`int`) [int]
260 Convert a Python integer to a plain C :c:expr:`int`.
261
262 ``I`` (:class:`int`) [unsigned int]
263 Convert a Python integer to a C :c:expr:`unsigned int`, without overflow
264 checking.
265
266 ``l`` (:class:`int`) [long int]
267 Convert a Python integer to a C :c:expr:`long int`.
268
269 ``k`` (:class:`int`) [unsigned long]
270 Convert a Python integer to a C :c:expr:`unsigned long` without
271 overflow checking.
272
273 ``L`` (:class:`int`) [long long]
274 Convert a Python integer to a C :c:expr:`long long`.
275
276 ``K`` (:class:`int`) [unsigned long long]
277 Convert a Python integer to a C :c:expr:`unsigned long long`
278 without overflow checking.
279
280 ``n`` (:class:`int`) [:c:type:`Py_ssize_t`]
281 Convert a Python integer to a C :c:type:`Py_ssize_t`.
282
283 ``c`` (:class:`bytes` or :class:`bytearray` of length 1) [char]
284 Convert a Python byte, represented as a :class:`bytes` or
285 :class:`bytearray` object of length 1, to a C :c:expr:`char`.
286
287 .. versionchanged:: 3.3
288 Allow :class:`bytearray` objects.
289
290 ``C`` (:class:`str` of length 1) [int]
291 Convert a Python character, represented as a :class:`str` object of
292 length 1, to a C :c:expr:`int`.
293
294 ``f`` (:class:`float`) [float]
295 Convert a Python floating-point number to a C :c:expr:`float`.
296
297 ``d`` (:class:`float`) [double]
298 Convert a Python floating-point number to a C :c:expr:`double`.
299
300 ``D`` (:class:`complex`) [Py_complex]
301 Convert a Python complex number to a C :c:type:`Py_complex` structure.
302
303 Other objects
304 -------------
305
306 ``O`` (object) [PyObject \*]
307 Store a Python object (without any conversion) in a C object pointer. The C
308 program thus receives the actual object that was passed. A new
309 :term:`strong reference` to the object is not created
310 (i.e. its reference count is not increased).
311 The pointer stored is not ``NULL``.
312
313 ``O!`` (object) [*typeobject*, PyObject \*]
314 Store a Python object in a C object pointer. This is similar to ``O``, but
315 takes two C arguments: the first is the address of a Python type object, the
316 second is the address of the C variable (of type :c:expr:`PyObject*`) into which
317 the object pointer is stored. If the Python object does not have the required
318 type, :exc:`TypeError` is raised.
319
320 .. _o_ampersand:
321
322 ``O&`` (object) [*converter*, *address*]
323 Convert a Python object to a C variable through a *converter* function. This
324 takes two arguments: the first is a function, the second is the address of a C
325 variable (of arbitrary type), converted to :c:expr:`void *`. The *converter*
326 function in turn is called as follows::
327
328 status = converter(object, address);
329
330 where *object* is the Python object to be converted and *address* is the
331 :c:expr:`void*` argument that was passed to the ``PyArg_Parse*`` function.
332 The returned *status* should be ``1`` for a successful conversion and ``0`` if
333 the conversion has failed. When the conversion fails, the *converter* function
334 should raise an exception and leave the content of *address* unmodified.
335
336 .. c:macro:: Py_CLEANUP_SUPPORTED
337 :no-typesetting:
338
339 If the *converter* returns :c:macro:`!Py_CLEANUP_SUPPORTED`, it may get called a
340 second time if the argument parsing eventually fails, giving the converter a
341 chance to release any memory that it had already allocated. In this second
342 call, the *object* parameter will be ``NULL``; *address* will have the same value
343 as in the original call.
344
345 Examples of converters: :c:func:`PyUnicode_FSConverter` and
346 :c:func:`PyUnicode_FSDecoder`.
347
348 .. versionchanged:: 3.1
349 :c:macro:`!Py_CLEANUP_SUPPORTED` was added.
350
351 ``p`` (:class:`bool`) [int]
352 Tests the value passed in for truth (a boolean **p**\ redicate) and converts
353 the result to its equivalent C true/false integer value.
354 Sets the int to ``1`` if the expression was true and ``0`` if it was false.
355 This accepts any valid Python value. See :ref:`truth` for more
356 information about how Python tests values for truth.
357
358 .. versionadded:: 3.3
359
360 ``(items)`` (:class:`tuple`) [*matching-items*]
361 The object must be a Python sequence whose length is the number of format units
362 in *items*. The C arguments must correspond to the individual format units in
363 *items*. Format units for sequences may be nested.
364
365 A few other characters have a meaning in a format string. These may not occur
366 inside nested parentheses. They are:
367
368 ``|``
369 Indicates that the remaining arguments in the Python argument list are optional.
370 The C variables corresponding to optional arguments should be initialized to
371 their default value --- when an optional argument is not specified,
372 :c:func:`PyArg_ParseTuple` does not touch the contents of the corresponding C
373 variable(s).
374
375 ``$``
376 :c:func:`PyArg_ParseTupleAndKeywords` only:
377 Indicates that the remaining arguments in the Python argument list are
378 keyword-only. Currently, all keyword-only arguments must also be optional
379 arguments, so ``|`` must always be specified before ``$`` in the format
380 string.
381
382 .. versionadded:: 3.3
383
384 ``:``
385 The list of format units ends here; the string after the colon is used as the
386 function name in error messages (the "associated value" of the exception that
387 :c:func:`PyArg_ParseTuple` raises).
388
389 ``;``
390 The list of format units ends here; the string after the semicolon is used as
391 the error message *instead* of the default error message. ``:`` and ``;``
392 mutually exclude each other.
393
394 Note that any Python object references which are provided to the caller are
395 *borrowed* references; do not release them
396 (i.e. do not decrement their reference count)!
397
398 Additional arguments passed to these functions must be addresses of variables
399 whose type is determined by the format string; these are used to store values
400 from the input tuple. There are a few cases, as described in the list of format
401 units above, where these parameters are used as input values; they should match
402 what is specified for the corresponding format unit in that case.
403
404 For the conversion to succeed, the *arg* object must match the format
405 and the format must be exhausted. On success, the
406 ``PyArg_Parse*`` functions return true, otherwise they return
407 false and raise an appropriate exception. When the
408 ``PyArg_Parse*`` functions fail due to conversion failure in one
409 of the format units, the variables at the addresses corresponding to that
410 and the following format units are left untouched.
411
412 API Functions
413 -------------
414
415 .. c:function:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
416
417 Parse the parameters of a function that takes only positional parameters into
418 local variables. Returns true on success; on failure, it returns false and
419 raises the appropriate exception.
420
421
422 .. c:function:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
423
424 Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list rather
425 than a variable number of arguments.
426
427
428 .. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, ...)
429
430 Parse the parameters of a function that takes both positional and keyword
431 parameters into local variables.
432 The *keywords* argument is a ``NULL``-terminated array of keyword parameter
433 names specified as null-terminated ASCII or UTF-8 encoded C strings.
434 Empty names denote
435 :ref:`positional-only parameters <positional-only_parameter>`.
436 Returns true on success; on failure, it returns false and raises the
437 appropriate exception.
438
439 .. note::
440
441 The *keywords* parameter declaration is :c:expr:`char * const *` in C and
442 :c:expr:`const char * const *` in C++.
443 This can be overridden with the :c:macro:`PY_CXX_CONST` macro.
444
445 .. versionchanged:: 3.6
446 Added support for :ref:`positional-only parameters
447 <positional-only_parameter>`.
448
449 .. versionchanged:: 3.13
450 The *keywords* parameter has now type :c:expr:`char * const *` in C and
451 :c:expr:`const char * const *` in C++, instead of :c:expr:`char **`.
452 Added support for non-ASCII keyword parameter names.
453
454
455
456 .. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, va_list vargs)
457
458 Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a
459 va_list rather than a variable number of arguments.
460
461
462 .. c:function:: int PyArg_ValidateKeywordArguments(PyObject *)
463
464 Ensure that the keys in the keywords argument dictionary are strings. This
465 is only needed if :c:func:`PyArg_ParseTupleAndKeywords` is not used, since the
466 latter already does this check.
467
468 .. versionadded:: 3.2
469
470
471 .. c:function:: int PyArg_Parse(PyObject *args, const char *format, ...)
472
473 Parse the parameter of a function that takes a single positional parameter
474 into a local variable. Returns true on success; on failure, it returns
475 false and raises the appropriate exception.
476
477 Example::
478
479 // Function using METH_O calling convention
480 static PyObject*
481 my_function(PyObject *module, PyObject *arg)
482 {
483 int value;
484 if (!PyArg_Parse(arg, "i:my_function", &value)) {
485 return NULL;
486 }
487 // ... use value ...
488 }
489
490
491 .. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
492
493 A simpler form of parameter retrieval which does not use a format string to
494 specify the types of the arguments. Functions which use this method to retrieve
495 their parameters should be declared as :c:macro:`METH_VARARGS` in function or
496 method tables. The tuple containing the actual parameters should be passed as
497 *args*; it must actually be a tuple. The length of the tuple must be at least
498 *min* and no more than *max*; *min* and *max* may be equal. Additional
499 arguments must be passed to the function, each of which should be a pointer to a
500 :c:expr:`PyObject*` variable; these will be filled in with the values from
501 *args*; they will contain :term:`borrowed references <borrowed reference>`.
502 The variables which correspond
503 to optional parameters not given by *args* will not be filled in; these should
504 be initialized by the caller. This function returns true on success and false if
505 *args* is not a tuple or contains the wrong number of elements; an exception
506 will be set if there was a failure.
507
508 This is an example of the use of this function, taken from the sources for the
509 :mod:`!_weakref` helper module for weak references::
510
511 static PyObject *
512 weakref_ref(PyObject *self, PyObject *args)
513 {
514 PyObject *object;
515 PyObject *callback = NULL;
516 PyObject *result = NULL;
517
518 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
519 result = PyWeakref_NewRef(object, callback);
520 }
521 return result;
522 }
523
524 The call to :c:func:`PyArg_UnpackTuple` in this example is entirely equivalent to
525 this call to :c:func:`PyArg_ParseTuple`::
526
527 PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
528
529 .. c:macro:: PY_CXX_CONST
530
531 The value to be inserted, if any, before :c:expr:`char * const *`
532 in the *keywords* parameter declaration of
533 :c:func:`PyArg_ParseTupleAndKeywords` and
534 :c:func:`PyArg_VaParseTupleAndKeywords`.
535 Default empty for C and ``const`` for C++
536 (:c:expr:`const char * const *`).
537 To override, define it to the desired value before including
538 :file:`Python.h`.
539
540 .. versionadded:: 3.13
541
542
543 ---------------
544 Building values
545 ---------------
546
547 .. c:function:: PyObject* Py_BuildValue(const char *format, ...)
548
549 Create a new value based on a format string similar to those accepted by the
550 ``PyArg_Parse*`` family of functions and a sequence of values. Returns
551 the value or ``NULL`` in the case of an error; an exception will be raised if
552 ``NULL`` is returned.
553
554 :c:func:`Py_BuildValue` does not always build a tuple. It builds a tuple only if
555 its format string contains two or more format units. If the format string is
556 empty, it returns ``None``; if it contains exactly one format unit, it returns
557 whatever object is described by that format unit. To force it to return a tuple
558 of size 0 or one, parenthesize the format string.
559
560 When memory buffers are passed as parameters to supply data to build objects, as
561 for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided
562 by the caller are never referenced by the objects created by
563 :c:func:`Py_BuildValue`. In other words, if your code invokes :c:func:`malloc`
564 and passes the allocated memory to :c:func:`Py_BuildValue`, your code is
565 responsible for calling :c:func:`free` for that memory once
566 :c:func:`Py_BuildValue` returns.
567
568 In the following description, the quoted form is the format unit; the entry in
569 (round) parentheses is the Python object type that the format unit will return;
570 and the entry in [square] brackets is the type of the C value(s) to be passed.
571
572 The characters space, tab, colon and comma are ignored in format strings (but
573 not within format units such as ``s#``). This can be used to make long format
574 strings a tad more readable.
575
576 ``s`` (:class:`str` or ``None``) [const char \*]
577 Convert a null-terminated C string to a Python :class:`str` object using ``'utf-8'``
578 encoding. If the C string pointer is ``NULL``, ``None`` is used.
579
580 ``s#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
581 Convert a C string and its length to a Python :class:`str` object using ``'utf-8'``
582 encoding. If the C string pointer is ``NULL``, the length is ignored and
583 ``None`` is returned.
584
585 ``y`` (:class:`bytes`) [const char \*]
586 This converts a C string to a Python :class:`bytes` object. If the C
587 string pointer is ``NULL``, ``None`` is returned.
588
589 ``y#`` (:class:`bytes`) [const char \*, :c:type:`Py_ssize_t`]
590 This converts a C string and its lengths to a Python object. If the C
591 string pointer is ``NULL``, ``None`` is returned.
592
593 ``z`` (:class:`str` or ``None``) [const char \*]
594 Same as ``s``.
595
596 ``z#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
597 Same as ``s#``.
598
599 ``u`` (:class:`str`) [const wchar_t \*]
600 Convert a null-terminated :c:type:`wchar_t` buffer of Unicode (UTF-16 or UCS-4)
601 data to a Python Unicode object. If the Unicode buffer pointer is ``NULL``,
602 ``None`` is returned.
603
604 ``u#`` (:class:`str`) [const wchar_t \*, :c:type:`Py_ssize_t`]
605 Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python
606 Unicode object. If the Unicode buffer pointer is ``NULL``, the length is ignored
607 and ``None`` is returned.
608
609 ``U`` (:class:`str` or ``None``) [const char \*]
610 Same as ``s``.
611
612 ``U#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
613 Same as ``s#``.
614
615 ``i`` (:class:`int`) [int]
616 Convert a plain C :c:expr:`int` to a Python integer object.
617
618 ``b`` (:class:`int`) [char]
619 Convert a plain C :c:expr:`char` to a Python integer object.
620
621 ``h`` (:class:`int`) [short int]
622 Convert a plain C :c:expr:`short int` to a Python integer object.
623
624 ``l`` (:class:`int`) [long int]
625 Convert a C :c:expr:`long int` to a Python integer object.
626
627 ``B`` (:class:`int`) [unsigned char]
628 Convert a C :c:expr:`unsigned char` to a Python integer object.
629
630 ``H`` (:class:`int`) [unsigned short int]
631 Convert a C :c:expr:`unsigned short int` to a Python integer object.
632
633 ``I`` (:class:`int`) [unsigned int]
634 Convert a C :c:expr:`unsigned int` to a Python integer object.
635
636 ``k`` (:class:`int`) [unsigned long]
637 Convert a C :c:expr:`unsigned long` to a Python integer object.
638
639 ``L`` (:class:`int`) [long long]
640 Convert a C :c:expr:`long long` to a Python integer object.
641
642 .. _capi-py-buildvalue-format-K:
643
644 ``K`` (:class:`int`) [unsigned long long]
645 Convert a C :c:expr:`unsigned long long` to a Python integer object.
646
647 ``n`` (:class:`int`) [:c:type:`Py_ssize_t`]
648 Convert a C :c:type:`Py_ssize_t` to a Python integer.
649
650 ``c`` (:class:`bytes` of length 1) [char]
651 Convert a C :c:expr:`int` representing a byte to a Python :class:`bytes` object of
652 length 1.
653
654 ``C`` (:class:`str` of length 1) [int]
655 Convert a C :c:expr:`int` representing a character to Python :class:`str`
656 object of length 1.
657
658 ``d`` (:class:`float`) [double]
659 Convert a C :c:expr:`double` to a Python floating-point number.
660
661 ``f`` (:class:`float`) [float]
662 Convert a C :c:expr:`float` to a Python floating-point number.
663
664 ``D`` (:class:`complex`) [Py_complex \*]
665 Convert a C :c:type:`Py_complex` structure to a Python complex number.
666
667 ``O`` (object) [PyObject \*]
668 Pass a Python object untouched but create a new
669 :term:`strong reference` to it
670 (i.e. its reference count is incremented by one).
671 If the object passed in is a ``NULL`` pointer, it is assumed
672 that this was caused because the call producing the argument found an error and
673 set an exception. Therefore, :c:func:`Py_BuildValue` will return ``NULL`` but won't
674 raise an exception. If no exception has been raised yet, :exc:`SystemError` is
675 set.
676
677 ``S`` (object) [PyObject \*]
678 Same as ``O``.
679
680 ``N`` (object) [PyObject \*]
681 Same as ``O``, except it doesn't create a new :term:`strong reference`.
682 Useful when the object is created by a call to an object constructor in the
683 argument list.
684
685 ``O&`` (object) [*converter*, *anything*]
686 Convert *anything* to a Python object through a *converter* function. The
687 function is called with *anything* (which should be compatible with :c:expr:`void*`)
688 as its argument and should return a "new" Python object, or ``NULL`` if an
689 error occurred.
690
691 ``(items)`` (:class:`tuple`) [*matching-items*]
692 Convert a sequence of C values to a Python tuple with the same number of items.
693
694 ``[items]`` (:class:`list`) [*matching-items*]
695 Convert a sequence of C values to a Python list with the same number of items.
696
697 ``{items}`` (:class:`dict`) [*matching-items*]
698 Convert a sequence of C values to a Python dictionary. Each pair of consecutive
699 C values adds one item to the dictionary, serving as key and value,
700 respectively.
701
702 If there is an error in the format string, the :exc:`SystemError` exception is
703 set and ``NULL`` returned.
704
705 .. c:function:: PyObject* Py_VaBuildValue(const char *format, va_list vargs)
706
707 Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list
708 rather than a variable number of arguments.