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