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 .. versionchanged:: 3.14
274 Use :meth:`~object.__index__` if available.
275
276 ``L`` (:class:`int`) [long long]
277 Convert a Python integer to a C :c:expr:`long long`.
278
279 ``K`` (:class:`int`) [unsigned long long]
280 Convert a Python integer to a C :c:expr:`unsigned long long`
281 without overflow checking.
282
283 .. versionchanged:: 3.14
284 Use :meth:`~object.__index__` if available.
285
286 ``n`` (:class:`int`) [:c:type:`Py_ssize_t`]
287 Convert a Python integer to a C :c:type:`Py_ssize_t`.
288
289 ``c`` (:class:`bytes` or :class:`bytearray` of length 1) [char]
290 Convert a Python byte, represented as a :class:`bytes` or
291 :class:`bytearray` object of length 1, to a C :c:expr:`char`.
292
293 .. versionchanged:: 3.3
294 Allow :class:`bytearray` objects.
295
296 ``C`` (:class:`str` of length 1) [int]
297 Convert a Python character, represented as a :class:`str` object of
298 length 1, to a C :c:expr:`int`.
299
300 ``f`` (:class:`float`) [float]
301 Convert a Python floating-point number to a C :c:expr:`float`.
302
303 ``d`` (:class:`float`) [double]
304 Convert a Python floating-point number to a C :c:expr:`double`.
305
306 ``D`` (:class:`complex`) [Py_complex]
307 Convert a Python complex number to a C :c:type:`Py_complex` structure.
308
309 Other objects
310 -------------
311
312 ``O`` (object) [PyObject \*]
313 Store a Python object (without any conversion) in a C object pointer. The C
314 program thus receives the actual object that was passed. A new
315 :term:`strong reference` to the object is not created
316 (i.e. its reference count is not increased).
317 The pointer stored is not ``NULL``.
318
319 ``O!`` (object) [*typeobject*, PyObject \*]
320 Store a Python object in a C object pointer. This is similar to ``O``, but
321 takes two C arguments: the first is the address of a Python type object, the
322 second is the address of the C variable (of type :c:expr:`PyObject*`) into which
323 the object pointer is stored. If the Python object does not have the required
324 type, :exc:`TypeError` is raised.
325
326 .. _o_ampersand:
327
328 ``O&`` (object) [*converter*, *address*]
329 Convert a Python object to a C variable through a *converter* function. This
330 takes two arguments: the first is a function, the second is the address of a C
331 variable (of arbitrary type), converted to :c:expr:`void *`. The *converter*
332 function in turn is called as follows::
333
334 status = converter(object, address);
335
336 where *object* is the Python object to be converted and *address* is the
337 :c:expr:`void*` argument that was passed to the ``PyArg_Parse*`` function.
338 The returned *status* should be ``1`` for a successful conversion and ``0`` if
339 the conversion has failed. When the conversion fails, the *converter* function
340 should raise an exception and leave the content of *address* unmodified.
341
342 .. c:macro:: Py_CLEANUP_SUPPORTED
343 :no-typesetting:
344
345 If the *converter* returns :c:macro:`!Py_CLEANUP_SUPPORTED`, it may get called a
346 second time if the argument parsing eventually fails, giving the converter a
347 chance to release any memory that it had already allocated. In this second
348 call, the *object* parameter will be ``NULL``; *address* will have the same value
349 as in the original call.
350
351 Examples of converters: :c:func:`PyUnicode_FSConverter` and
352 :c:func:`PyUnicode_FSDecoder`.
353
354 .. versionchanged:: 3.1
355 :c:macro:`!Py_CLEANUP_SUPPORTED` was added.
356
357 ``p`` (:class:`bool`) [int]
358 Tests the value passed in for truth (a boolean **p**\ redicate) and converts
359 the result to its equivalent C true/false integer value.
360 Sets the int to ``1`` if the expression was true and ``0`` if it was false.
361 This accepts any valid Python value. See :ref:`truth` for more
362 information about how Python tests values for truth.
363
364 .. versionadded:: 3.3
365
366 ``(items)`` (sequence) [*matching-items*]
367 The object must be a Python sequence (except :class:`str`, :class:`bytes`
368 or :class:`bytearray`) whose length is the number of format units
369 in *items*. The C arguments must correspond to the individual format units in
370 *items*. Format units for sequences may be nested.
371
372 If *items* contains format units which store a :ref:`borrowed buffer
373 <c-arg-borrowed-buffer>` (``s``, ``s#``, ``z``, ``z#``, ``y``, or ``y#``)
374 or a :term:`borrowed reference` (``S``, ``Y``, ``U``, ``O``, or ``O!``),
375 the object must be a Python tuple.
376 The *converter* for the ``O&`` format unit in *items* must not store
377 a borrowed buffer or a borrowed reference.
378
379 .. versionchanged:: 3.14
380 :class:`str` and :class:`bytearray` objects no longer accepted as a sequence.
381
382 .. deprecated:: 3.14
383 Non-tuple sequences are deprecated if *items* contains format units
384 which store a borrowed buffer or a borrowed reference.
385
386 A few other characters have a meaning in a format string. These may not occur
387 inside nested parentheses. They are:
388
389 ``|``
390 Indicates that the remaining arguments in the Python argument list are optional.
391 The C variables corresponding to optional arguments should be initialized to
392 their default value --- when an optional argument is not specified,
393 :c:func:`PyArg_ParseTuple` does not touch the contents of the corresponding C
394 variable(s).
395
396 ``$``
397 :c:func:`PyArg_ParseTupleAndKeywords` only:
398 Indicates that the remaining arguments in the Python argument list are
399 keyword-only. Currently, all keyword-only arguments must also be optional
400 arguments, so ``|`` must always be specified before ``$`` in the format
401 string.
402
403 .. versionadded:: 3.3
404
405 ``:``
406 The list of format units ends here; the string after the colon is used as the
407 function name in error messages (the "associated value" of the exception that
408 :c:func:`PyArg_ParseTuple` raises).
409
410 ``;``
411 The list of format units ends here; the string after the semicolon is used as
412 the error message *instead* of the default error message. ``:`` and ``;``
413 mutually exclude each other.
414
415 Note that any Python object references which are provided to the caller are
416 *borrowed* references; do not release them
417 (i.e. do not decrement their reference count)!
418
419 Additional arguments passed to these functions must be addresses of variables
420 whose type is determined by the format string; these are used to store values
421 from the input tuple. There are a few cases, as described in the list of format
422 units above, where these parameters are used as input values; they should match
423 what is specified for the corresponding format unit in that case.
424
425 For the conversion to succeed, the *arg* object must match the format
426 and the format must be exhausted. On success, the
427 ``PyArg_Parse*`` functions return true, otherwise they return
428 false and raise an appropriate exception. When the
429 ``PyArg_Parse*`` functions fail due to conversion failure in one
430 of the format units, the variables at the addresses corresponding to that
431 and the following format units are left untouched.
432
433 API Functions
434 -------------
435
436 .. c:function:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
437
438 Parse the parameters of a function that takes only positional parameters into
439 local variables. Returns true on success; on failure, it returns false and
440 raises the appropriate exception.
441
442
443 .. c:function:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
444
445 Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list rather
446 than a variable number of arguments.
447
448
449 .. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, ...)
450
451 Parse the parameters of a function that takes both positional and keyword
452 parameters into local variables.
453 The *keywords* argument is a ``NULL``-terminated array of keyword parameter
454 names specified as null-terminated ASCII or UTF-8 encoded C strings.
455 Empty names denote
456 :ref:`positional-only parameters <positional-only_parameter>`.
457 Returns true on success; on failure, it returns false and raises the
458 appropriate exception.
459
460 .. note::
461
462 The *keywords* parameter declaration is :c:expr:`char * const *` in C and
463 :c:expr:`const char * const *` in C++.
464 This can be overridden with the :c:macro:`PY_CXX_CONST` macro.
465
466 .. versionchanged:: 3.6
467 Added support for :ref:`positional-only parameters
468 <positional-only_parameter>`.
469
470 .. versionchanged:: 3.13
471 The *keywords* parameter has now type :c:expr:`char * const *` in C and
472 :c:expr:`const char * const *` in C++, instead of :c:expr:`char **`.
473 Added support for non-ASCII keyword parameter names.
474
475
476
477 .. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char * const *keywords, va_list vargs)
478
479 Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a
480 va_list rather than a variable number of arguments.
481
482
483 .. c:function:: int PyArg_ValidateKeywordArguments(PyObject *)
484
485 Ensure that the keys in the keywords argument dictionary are strings. This
486 is only needed if :c:func:`PyArg_ParseTupleAndKeywords` is not used, since the
487 latter already does this check.
488
489 .. versionadded:: 3.2
490
491
492 .. c:function:: int PyArg_Parse(PyObject *args, const char *format, ...)
493
494 Parse the parameter of a function that takes a single positional parameter
495 into a local variable. Returns true on success; on failure, it returns
496 false and raises the appropriate exception.
497
498 Example::
499
500 // Function using METH_O calling convention
501 static PyObject*
502 my_function(PyObject *module, PyObject *arg)
503 {
504 int value;
505 if (!PyArg_Parse(arg, "i:my_function", &value)) {
506 return NULL;
507 }
508 // ... use value ...
509 }
510
511
512 .. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
513
514 A simpler form of parameter retrieval which does not use a format string to
515 specify the types of the arguments. Functions which use this method to retrieve
516 their parameters should be declared as :c:macro:`METH_VARARGS` in function or
517 method tables. The tuple containing the actual parameters should be passed as
518 *args*; it must actually be a tuple. The length of the tuple must be at least
519 *min* and no more than *max*; *min* and *max* may be equal. Additional
520 arguments must be passed to the function, each of which should be a pointer to a
521 :c:expr:`PyObject*` variable; these will be filled in with the values from
522 *args*; they will contain :term:`borrowed references <borrowed reference>`.
523 The variables which correspond
524 to optional parameters not given by *args* will not be filled in; these should
525 be initialized by the caller. This function returns true on success and false if
526 *args* is not a tuple or contains the wrong number of elements; an exception
527 will be set if there was a failure.
528
529 This is an example of the use of this function, taken from the sources for the
530 :mod:`!_weakref` helper module for weak references::
531
532 static PyObject *
533 weakref_ref(PyObject *self, PyObject *args)
534 {
535 PyObject *object;
536 PyObject *callback = NULL;
537 PyObject *result = NULL;
538
539 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
540 result = PyWeakref_NewRef(object, callback);
541 }
542 return result;
543 }
544
545 The call to :c:func:`PyArg_UnpackTuple` in this example is entirely equivalent to
546 this call to :c:func:`PyArg_ParseTuple`::
547
548 PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
549
550 .. c:macro:: PY_CXX_CONST
551
552 The value to be inserted, if any, before :c:expr:`char * const *`
553 in the *keywords* parameter declaration of
554 :c:func:`PyArg_ParseTupleAndKeywords` and
555 :c:func:`PyArg_VaParseTupleAndKeywords`.
556 Default empty for C and ``const`` for C++
557 (:c:expr:`const char * const *`).
558 To override, define it to the desired value before including
559 :file:`Python.h`.
560
561 .. versionadded:: 3.13
562
563
564 ---------------
565 Building values
566 ---------------
567
568 .. c:function:: PyObject* Py_BuildValue(const char *format, ...)
569
570 Create a new value based on a format string similar to those accepted by the
571 ``PyArg_Parse*`` family of functions and a sequence of values. Returns
572 the value or ``NULL`` in the case of an error; an exception will be raised if
573 ``NULL`` is returned.
574
575 :c:func:`Py_BuildValue` does not always build a tuple. It builds a tuple only if
576 its format string contains two or more format units. If the format string is
577 empty, it returns ``None``; if it contains exactly one format unit, it returns
578 whatever object is described by that format unit. To force it to return a tuple
579 of size 0 or one, parenthesize the format string.
580
581 When memory buffers are passed as parameters to supply data to build objects, as
582 for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided
583 by the caller are never referenced by the objects created by
584 :c:func:`Py_BuildValue`. In other words, if your code invokes :c:func:`malloc`
585 and passes the allocated memory to :c:func:`Py_BuildValue`, your code is
586 responsible for calling :c:func:`free` for that memory once
587 :c:func:`Py_BuildValue` returns.
588
589 In the following description, the quoted form is the format unit; the entry in
590 (round) parentheses is the Python object type that the format unit will return;
591 and the entry in [square] brackets is the type of the C value(s) to be passed.
592
593 The characters space, tab, colon and comma are ignored in format strings (but
594 not within format units such as ``s#``). This can be used to make long format
595 strings a tad more readable.
596
597 ``s`` (:class:`str` or ``None``) [const char \*]
598 Convert a null-terminated C string to a Python :class:`str` object using ``'utf-8'``
599 encoding. If the C string pointer is ``NULL``, ``None`` is used.
600
601 ``s#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
602 Convert a C string and its length to a Python :class:`str` object using ``'utf-8'``
603 encoding. If the C string pointer is ``NULL``, the length is ignored and
604 ``None`` is returned.
605
606 ``y`` (:class:`bytes`) [const char \*]
607 This converts a C string to a Python :class:`bytes` object. If the C
608 string pointer is ``NULL``, ``None`` is returned.
609
610 ``y#`` (:class:`bytes`) [const char \*, :c:type:`Py_ssize_t`]
611 This converts a C string and its lengths to a Python object. If the C
612 string pointer is ``NULL``, ``None`` is returned.
613
614 ``z`` (:class:`str` or ``None``) [const char \*]
615 Same as ``s``.
616
617 ``z#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
618 Same as ``s#``.
619
620 ``u`` (:class:`str`) [const wchar_t \*]
621 Convert a null-terminated :c:type:`wchar_t` buffer of Unicode (UTF-16 or UCS-4)
622 data to a Python Unicode object. If the Unicode buffer pointer is ``NULL``,
623 ``None`` is returned.
624
625 ``u#`` (:class:`str`) [const wchar_t \*, :c:type:`Py_ssize_t`]
626 Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python
627 Unicode object. If the Unicode buffer pointer is ``NULL``, the length is ignored
628 and ``None`` is returned.
629
630 ``U`` (:class:`str` or ``None``) [const char \*]
631 Same as ``s``.
632
633 ``U#`` (:class:`str` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
634 Same as ``s#``.
635
636 ``i`` (:class:`int`) [int]
637 Convert a plain C :c:expr:`int` to a Python integer object.
638
639 ``b`` (:class:`int`) [char]
640 Convert a plain C :c:expr:`char` to a Python integer object.
641
642 ``h`` (:class:`int`) [short int]
643 Convert a plain C :c:expr:`short int` to a Python integer object.
644
645 ``l`` (:class:`int`) [long int]
646 Convert a C :c:expr:`long int` to a Python integer object.
647
648 ``B`` (:class:`int`) [unsigned char]
649 Convert a C :c:expr:`unsigned char` to a Python integer object.
650
651 ``H`` (:class:`int`) [unsigned short int]
652 Convert a C :c:expr:`unsigned short int` to a Python integer object.
653
654 ``I`` (:class:`int`) [unsigned int]
655 Convert a C :c:expr:`unsigned int` to a Python integer object.
656
657 ``k`` (:class:`int`) [unsigned long]
658 Convert a C :c:expr:`unsigned long` to a Python integer object.
659
660 ``L`` (:class:`int`) [long long]
661 Convert a C :c:expr:`long long` to a Python integer object.
662
663 .. _capi-py-buildvalue-format-K:
664
665 ``K`` (:class:`int`) [unsigned long long]
666 Convert a C :c:expr:`unsigned long long` to a Python integer object.
667
668 ``n`` (:class:`int`) [:c:type:`Py_ssize_t`]
669 Convert a C :c:type:`Py_ssize_t` to a Python integer.
670
671 ``p`` (:class:`bool`) [int]
672 Convert a C :c:expr:`int` to a Python :class:`bool` object.
673
674 Be aware that this format requires an ``int`` argument.
675 Unlike most other contexts in C, variadic arguments are not coerced to
676 a suitable type automatically.
677 You can convert another type (for example, a pointer or a float) to a
678 suitable ``int`` value using ``(x) ? 1 : 0`` or ``!!x``.
679
680 .. versionadded:: 3.14
681
682 ``c`` (:class:`bytes` of length 1) [char]
683 Convert a C :c:expr:`int` representing a byte to a Python :class:`bytes` object of
684 length 1.
685
686 ``C`` (:class:`str` of length 1) [int]
687 Convert a C :c:expr:`int` representing a character to Python :class:`str`
688 object of length 1.
689
690 ``d`` (:class:`float`) [double]
691 Convert a C :c:expr:`double` to a Python floating-point number.
692
693 ``f`` (:class:`float`) [float]
694 Convert a C :c:expr:`float` to a Python floating-point number.
695
696 ``D`` (:class:`complex`) [Py_complex \*]
697 Convert a C :c:type:`Py_complex` structure to a Python complex number.
698
699 ``O`` (object) [PyObject \*]
700 Pass a Python object untouched but create a new
701 :term:`strong reference` to it
702 (i.e. its reference count is incremented by one).
703 If the object passed in is a ``NULL`` pointer, it is assumed
704 that this was caused because the call producing the argument found an error and
705 set an exception. Therefore, :c:func:`Py_BuildValue` will return ``NULL`` but won't
706 raise an exception. If no exception has been raised yet, :exc:`SystemError` is
707 set.
708
709 ``S`` (object) [PyObject \*]
710 Same as ``O``.
711
712 ``N`` (object) [PyObject \*]
713 Same as ``O``, except it doesn't create a new :term:`strong reference`.
714 Useful when the object is created by a call to an object constructor in the
715 argument list.
716
717 ``O&`` (object) [*converter*, *anything*]
718 Convert *anything* to a Python object through a *converter* function. The
719 function is called with *anything* (which should be compatible with :c:expr:`void*`)
720 as its argument and should return a "new" Python object, or ``NULL`` if an
721 error occurred.
722
723 ``(items)`` (:class:`tuple`) [*matching-items*]
724 Convert a sequence of C values to a Python tuple with the same number of items.
725
726 ``[items]`` (:class:`list`) [*matching-items*]
727 Convert a sequence of C values to a Python list with the same number of items.
728
729 ``{items}`` (:class:`dict`) [*matching-items*]
730 Convert a sequence of C values to a Python dictionary. Each pair of consecutive
731 C values adds one item to the dictionary, serving as key and value,
732 respectively.
733
734 If there is an error in the format string, the :exc:`SystemError` exception is
735 set and ``NULL`` returned.
736
737 .. c:function:: PyObject* Py_VaBuildValue(const char *format, va_list vargs)
738
739 Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list
740 rather than a variable number of arguments.