summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/c-api%2Farg.html
blob: fff2a6263fc71fe296b78c05b5b90f0f8f4e9e68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
 <span id="arg-parsing"></span><h1>Parsing arguments and building values</h1> <p>These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in <a class="reference internal" href="../extending/index#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a>.</p> <p>The first three of these functions described, <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a>, <a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code>PyArg_ParseTupleAndKeywords()</code></a>, and <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code>PyArg_Parse()</code></a>, all use <em>format strings</em> which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions.</p> <section id="parsing-arguments"> <h2>Parsing arguments</h2> <p>A format string consists of zero or more “format units.” A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed.</p> <section id="strings-and-buffers"> <h3>Strings and buffers</h3> <p>These formats allow accessing an object as a contiguous chunk of memory. You don’t have to provide raw storage for the returned unicode or bytes area.</p> <p>Unless otherwise stated, buffers are not NUL-terminated.</p> <p>There are three ways strings and buffers can be converted to C:</p> <ul> <li>Formats such as <code>y*</code> and <code>s*</code> fill a <a class="reference internal" href="buffer#c.Py_buffer" title="Py_buffer"><code>Py_buffer</code></a> structure. This locks the underlying buffer so that the caller can subsequently use the buffer even inside a <a class="reference internal" href="init#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code>Py_BEGIN_ALLOW_THREADS</code></a> block without the risk of mutable data being resized or destroyed. As a result, <strong>you have to call</strong> <a class="reference internal" href="buffer#c.PyBuffer_Release" title="PyBuffer_Release"><code>PyBuffer_Release()</code></a> after you have finished processing the data (or in any early abort case).</li> <li>The <code>es</code>, <code>es#</code>, <code>et</code> and <code>et#</code> formats allocate the result buffer. <strong>You have to call</strong> <a class="reference internal" href="memory#c.PyMem_Free" title="PyMem_Free"><code>PyMem_Free()</code></a> after you have finished processing the data (or in any early abort case).</li> <li>
<p id="c-arg-borrowed-buffer">Other formats take a <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> or a read-only <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, such as <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a>, and provide a <code>const char *</code> pointer to its buffer. In this case the buffer is “borrowed”: it is managed by the corresponding Python object, and shares the lifetime of this object. You won’t have to release any memory yourself.</p> <p>To ensure that the underlying buffer may be safely borrowed, the object’s <a class="reference internal" href="typeobj#c.PyBufferProcs.bf_releasebuffer" title="PyBufferProcs.bf_releasebuffer"><code>PyBufferProcs.bf_releasebuffer</code></a> field must be <code>NULL</code>. This disallows common mutable objects such as <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>, but also some read-only objects such as <a class="reference internal" href="../library/stdtypes#memoryview" title="memoryview"><code>memoryview</code></a> of <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a>.</p> <p>Besides this <code>bf_releasebuffer</code> requirement, there is no check to verify whether the input object is immutable (e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the data).</p> </li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>For all <code>#</code> variants of formats (<code>s#</code>, <code>y#</code>, etc.), the macro <code>PY_SSIZE_T_CLEAN</code> must be defined before including <code>Python.h</code>. On Python 3.9 and older, the type of the length argument is <a class="reference internal" href="intro#c.Py_ssize_t" title="Py_ssize_t"><code>Py_ssize_t</code></a> if the <code>PY_SSIZE_T_CLEAN</code> macro is defined, or int otherwise.</p> </div> <dl> <dt>
<code>s (str) [const char *]</code> </dt>
<dd>
<p>Convert a Unicode object to a C pointer to a character string. A pointer to an existing string is stored in the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded null code points; if it does, a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> exception is raised. Unicode objects are converted to C strings using <code>'utf-8'</code> encoding. If this conversion fails, a <a class="reference internal" href="../library/exceptions#UnicodeError" title="UnicodeError"><code>UnicodeError</code></a> is raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This format does not accept <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like objects</span></a>. If you want to accept filesystem paths and convert them to C character strings, it is preferable to use the <code>O&amp;</code> format with <a class="reference internal" href="unicode#c.PyUnicode_FSConverter" title="PyUnicode_FSConverter"><code>PyUnicode_FSConverter()</code></a> as <em>converter</em>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Previously, <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> was raised when embedded null code points were encountered in the Python string.</p> </div> </dd> <dt>
<code>s* (str or bytes-like object) [Py_buffer]</code> </dt>
<dd>
<p>This format accepts Unicode objects as well as bytes-like objects. It fills a <a class="reference internal" href="buffer#c.Py_buffer" title="Py_buffer"><code>Py_buffer</code></a> structure provided by the caller. In this case the resulting C string may contain embedded NUL bytes. Unicode objects are converted to C strings using <code>'utf-8'</code> encoding.</p> </dd> <dt>
<code>s# (str, read-only bytes-like object) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>Like <code>s*</code>, except that it provides a <a class="reference internal" href="#c-arg-borrowed-buffer"><span class="std std-ref">borrowed buffer</span></a>. The result is stored into two C variables, the first one a pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects are converted to C strings using <code>'utf-8'</code> encoding.</p> </dd> <dt>
<code>z (str or None) [const char *]</code> </dt>
<dd>
<p>Like <code>s</code>, but the Python object may also be <code>None</code>, in which case the C pointer is set to <code>NULL</code>.</p> </dd> <dt>
<code>z* (str, bytes-like object or None) [Py_buffer]</code> </dt>
<dd>
<p>Like <code>s*</code>, but the Python object may also be <code>None</code>, in which case the <code>buf</code> member of the <a class="reference internal" href="buffer#c.Py_buffer" title="Py_buffer"><code>Py_buffer</code></a> structure is set to <code>NULL</code>.</p> </dd> <dt>
<code>z# (str, read-only bytes-like object or None) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>Like <code>s#</code>, but the Python object may also be <code>None</code>, in which case the C pointer is set to <code>NULL</code>.</p> </dd> <dt>
<code>y (read-only bytes-like object) [const char *]</code> </dt>
<dd>
<p>This format converts a bytes-like object to a C pointer to a <a class="reference internal" href="#c-arg-borrowed-buffer"><span class="std std-ref">borrowed</span></a> character string; it does not accept Unicode objects. The bytes buffer must not contain embedded null bytes; if it does, a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> exception is raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Previously, <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> was raised when embedded null bytes were encountered in the bytes buffer.</p> </div> </dd> <dt>
<code>y* (bytes-like object) [Py_buffer]</code> </dt>
<dd>
<p>This variant on <code>s*</code> doesn’t accept Unicode objects, only bytes-like objects. <strong>This is the recommended way to accept binary data.</strong></p> </dd> <dt>
<code>y# (read-only bytes-like object) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>This variant on <code>s#</code> doesn’t accept Unicode objects, only bytes-like objects.</p> </dd> <dt>
<code>S (bytes) [PyBytesObject *]</code> </dt>
<dd>
<p>Requires that the Python object is a <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> object, without attempting any conversion. Raises <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the object is not a bytes object. The C variable may also be declared as <span class="c-expr sig sig-inline c"><a class="reference internal" href="structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>.</p> </dd> <dt>
<code>Y (bytearray) [PyByteArrayObject *]</code> </dt>
<dd>
<p>Requires that the Python object is a <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> object, without attempting any conversion. Raises <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the object is not a <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> object. The C variable may also be declared as <span class="c-expr sig sig-inline c"><a class="reference internal" href="structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>.</p> </dd> <dt>
<code>U (str) [PyObject *]</code> </dt>
<dd>
<p>Requires that the Python object is a Unicode object, without attempting any conversion. Raises <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the object is not a Unicode object. The C variable may also be declared as <span class="c-expr sig sig-inline c"><a class="reference internal" href="structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>.</p> </dd> <dt>
<code>w* (read-write bytes-like object) [Py_buffer]</code> </dt>
<dd>
<p>This format accepts any object which implements the read-write buffer interface. It fills a <a class="reference internal" href="buffer#c.Py_buffer" title="Py_buffer"><code>Py_buffer</code></a> structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call <a class="reference internal" href="buffer#c.PyBuffer_Release" title="PyBuffer_Release"><code>PyBuffer_Release()</code></a> when it is done with the buffer.</p> </dd> <dt>
<code>es (str) [const char *encoding, char **buffer]</code> </dt>
<dd>
<p>This variant on <code>s</code> is used for encoding Unicode into a character buffer. It only works for encoded data without embedded NUL bytes.</p> <p>This format requires two arguments. The first is only used as input, and must be a <span class="c-expr sig sig-inline c"><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="p">*</span></span> which points to the name of an encoding as a NUL-terminated string, or <code>NULL</code>, in which case <code>'utf-8'</code> encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span><span class="p">*</span></span>; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument.</p> <p><a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust <em>*buffer</em> to reference the newly allocated storage. The caller is responsible for calling <a class="reference internal" href="memory#c.PyMem_Free" title="PyMem_Free"><code>PyMem_Free()</code></a> to free the allocated buffer after use.</p> </dd> <dt>
<code>et (str, bytes or bytearray) [const char *encoding, char **buffer]</code> </dt>
<dd>
<p>Same as <code>es</code> except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.</p> </dd> <dt>
<code>es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]</code> </dt>
<dd>
<p>This variant on <code>s#</code> is used for encoding Unicode into a character buffer. Unlike the <code>es</code> format, this variant allows input data which contains NUL characters.</p> <p>It requires three arguments. The first is only used as input, and must be a <span class="c-expr sig sig-inline c"><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="p">*</span></span> which points to the name of an encoding as a NUL-terminated string, or <code>NULL</code>, in which case <code>'utf-8'</code> encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span><span class="p">*</span></span>; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer.</p> <p>There are two modes of operation:</p> <p>If <em>*buffer</em> points a <code>NULL</code> pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set <em>*buffer</em> to reference the newly allocated storage. The caller is responsible for calling <a class="reference internal" href="memory#c.PyMem_Free" title="PyMem_Free"><code>PyMem_Free()</code></a> to free the allocated buffer after usage.</p> <p>If <em>*buffer</em> points to a non-<code>NULL</code> pointer (an already allocated buffer), <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> will use this location as the buffer and interpret the initial value of <em>*buffer_length</em> as the buffer size. It will then copy the encoded data into the buffer and NUL-terminate it. If the buffer is not large enough, a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be set.</p> <p>In both cases, <em>*buffer_length</em> is set to the length of the encoded data without the trailing NUL byte.</p> </dd> <dt>
<code>et# (str, bytes or bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]</code> </dt>
<dd>
<p>Same as <code>es#</code> except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.</p> </dd> </dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><code>u</code>, <code>u#</code>, <code>Z</code>, and <code>Z#</code> are removed because they used a legacy <code>Py_UNICODE*</code> representation.</p> </div> </section> <section id="numbers"> <h3>Numbers</h3> <dl> <dt>
<code>b (int) [unsigned char]</code> </dt>
<dd>
<p>Convert a nonnegative Python integer to an unsigned tiny int, stored in a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">char</span></span>.</p> </dd> <dt>
<code>B (int) [unsigned char]</code> </dt>
<dd>
<p>Convert a Python integer to a tiny int without overflow checking, stored in a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">char</span></span>.</p> </dd> <dt>
<code>h (int) [short int]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">short</span><span class="w"> </span><span class="kt">int</span></span>.</p> </dd> <dt>
<code>H (int) [unsigned short int]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">short</span><span class="w"> </span><span class="kt">int</span></span>, without overflow checking.</p> </dd> <dt>
<code>i (int) [int]</code> </dt>
<dd>
<p>Convert a Python integer to a plain C <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>.</p> </dd> <dt>
<code>I (int) [unsigned int]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span></span>, without overflow checking.</p> </dd> <dt>
<code>l (int) [long int]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">long</span><span class="w"> </span><span class="kt">int</span></span>.</p> </dd> <dt>
<code>k (int) [unsigned long]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span></span> without overflow checking.</p> </dd> <dt>
<code>L (int) [long long]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span>.</p> </dd> <dt>
<code>K (int) [unsigned long long]</code> </dt>
<dd>
<p>Convert a Python integer to a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span> without overflow checking.</p> </dd> <dt>
<code>n (int) [Py_ssize_t]</code> </dt>
<dd>
<p>Convert a Python integer to a C <a class="reference internal" href="intro#c.Py_ssize_t" title="Py_ssize_t"><code>Py_ssize_t</code></a>.</p> </dd> <dt>
<code>c (bytes or bytearray of length 1) [char]</code> </dt>
<dd>
<p>Convert a Python byte, represented as a <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> object of length 1, to a C <span class="c-expr sig sig-inline c"><span class="kt">char</span></span>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Allow <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> objects.</p> </div> </dd> <dt>
<code>C (str of length 1) [int]</code> </dt>
<dd>
<p>Convert a Python character, represented as a <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> object of length 1, to a C <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>.</p> </dd> <dt>
<code>f (float) [float]</code> </dt>
<dd>
<p>Convert a Python floating point number to a C <span class="c-expr sig sig-inline c"><span class="kt">float</span></span>.</p> </dd> <dt>
<code>d (float) [double]</code> </dt>
<dd>
<p>Convert a Python floating point number to a C <span class="c-expr sig sig-inline c"><span class="kt">double</span></span>.</p> </dd> <dt>
<code>D (complex) [Py_complex]</code> </dt>
<dd>
<p>Convert a Python complex number to a C <a class="reference internal" href="complex#c.Py_complex" title="Py_complex"><code>Py_complex</code></a> structure.</p> </dd> </dl> </section> <section id="other-objects"> <h3>Other objects</h3> <dl class="simple"> <dt>
<code>O (object) [PyObject *]</code> </dt>
<dd>
<p>Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. A new <a class="reference internal" href="../glossary#term-strong-reference"><span class="xref std std-term">strong reference</span></a> to the object is not created (i.e. its reference count is not increased). The pointer stored is not <code>NULL</code>.</p> </dd> <dt>
<code>O! (object) [typeobject, PyObject *]</code> </dt>
<dd>
<p>Store a Python object in a C object pointer. This is similar to <code>O</code>, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type <span class="c-expr sig sig-inline c"><a class="reference internal" href="structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>) into which the object pointer is stored. If the Python object does not have the required type, <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> </dd> </dl> <dl id="o-ampersand"> <dt>
<code>O&amp; (object) [converter, anything]</code> </dt>
<dd>
<p>Convert a Python object to a C variable through a <em>converter</em> function. This takes two arguments: the first is a function, the second is the address of a C variable (of arbitrary type), converted to <span class="c-expr sig sig-inline c"><span class="kt">void</span><span class="p">*</span></span>. The <em>converter</em> function in turn is called as follows:</p> <pre data-language="c">status = converter(object, address);
</pre> <p>where <em>object</em> is the Python object to be converted and <em>address</em> is the <span class="c-expr sig sig-inline c"><span class="kt">void</span><span class="p">*</span></span> argument that was passed to the <code>PyArg_Parse*</code> function. The returned <em>status</em> should be <code>1</code> for a successful conversion and <code>0</code> if the conversion has failed. When the conversion fails, the <em>converter</em> function should raise an exception and leave the content of <em>address</em> unmodified.</p> <p>If the <em>converter</em> returns <code>Py_CLEANUP_SUPPORTED</code>, it may get called a second time if the argument parsing eventually fails, giving the converter a chance to release any memory that it had already allocated. In this second call, the <em>object</em> parameter will be <code>NULL</code>; <em>address</em> will have the same value as in the original call.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span><code>Py_CLEANUP_SUPPORTED</code> was added.</p> </div> </dd> <dt>
<code>p (bool) [int]</code> </dt>
<dd>
<p>Tests the value passed in for truth (a boolean <strong>p</strong>redicate) and converts the result to its equivalent C true/false integer value. Sets the int to <code>1</code> if the expression was true and <code>0</code> if it was false. This accepts any valid Python value. See <a class="reference internal" href="../library/stdtypes#truth"><span class="std std-ref">Truth Value Testing</span></a> for more information about how Python tests values for truth.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd> <dt>
<code>(items) (tuple) [matching-items]</code> </dt>
<dd>
<p>The object must be a Python sequence whose length is the number of format units in <em>items</em>. The C arguments must correspond to the individual format units in <em>items</em>. Format units for sequences may be nested.</p> </dd> </dl> <p>It is possible to pass “long” integers (integers whose value exceeds the platform’s <code>LONG_MAX</code>) however no proper range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive the value (actually, the semantics are inherited from downcasts in C — your mileage may vary).</p> <p>A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are:</p> <dl> <dt>
<code>|</code> </dt>
<dd>
<p>Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding to optional arguments should be initialized to their default value — when an optional argument is not specified, <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> does not touch the contents of the corresponding C variable(s).</p> </dd> <dt>
<code>$</code> </dt>
<dd>
<p><a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code>PyArg_ParseTupleAndKeywords()</code></a> only: Indicates that the remaining arguments in the Python argument list are keyword-only. Currently, all keyword-only arguments must also be optional arguments, so <code>|</code> must always be specified before <code>$</code> in the format string.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd> <dt>
<code>:</code> </dt>
<dd>
<p>The list of format units ends here; the string after the colon is used as the function name in error messages (the “associated value” of the exception that <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> raises).</p> </dd> <dt>
<code>;</code> </dt>
<dd>
<p>The list of format units ends here; the string after the semicolon is used as the error message <em>instead</em> of the default error message. <code>:</code> and <code>;</code> mutually exclude each other.</p> </dd> </dl> <p>Note that any Python object references which are provided to the caller are <em>borrowed</em> references; do not release them (i.e. do not decrement their reference count)!</p> <p>Additional arguments passed to these functions must be addresses of variables whose type is determined by the format string; these are used to store values from the input tuple. There are a few cases, as described in the list of format units above, where these parameters are used as input values; they should match what is specified for the corresponding format unit in that case.</p> <p>For the conversion to succeed, the <em>arg</em> object must match the format and the format must be exhausted. On success, the <code>PyArg_Parse*</code> functions return true, otherwise they return false and raise an appropriate exception. When the <code>PyArg_Parse*</code> functions fail due to conversion failure in one of the format units, the variables at the addresses corresponding to that and the following format units are left untouched.</p> </section> <section id="api-functions"> <h3>API Functions</h3> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_ParseTuple">
<code>int PyArg_ParseTuple(PyObject *args, const char *format, ...)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Parse the parameters of a function that takes only positional parameters into local variables. Returns true on success; on failure, it returns false and raises the appropriate exception.</p> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_VaParse">
<code>int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Identical to <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a>, except that it accepts a va_list rather than a variable number of arguments.</p> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_ParseTupleAndKeywords">
<code>int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Parse the parameters of a function that takes both positional and keyword parameters into local variables. The <em>keywords</em> argument is a <code>NULL</code>-terminated array of keyword parameter names. Empty names denote <a class="reference internal" href="../glossary#positional-only-parameter"><span class="std std-ref">positional-only parameters</span></a>. Returns true on success; on failure, it returns false and raises the appropriate exception.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added support for <a class="reference internal" href="../glossary#positional-only-parameter"><span class="std std-ref">positional-only parameters</span></a>.</p> </div> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_VaParseTupleAndKeywords">
<code>int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Identical to <a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code>PyArg_ParseTupleAndKeywords()</code></a>, except that it accepts a va_list rather than a variable number of arguments.</p> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_ValidateKeywordArguments">
<code>int PyArg_ValidateKeywordArguments(PyObject*)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Ensure that the keys in the keywords argument dictionary are strings. This is only needed if <a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code>PyArg_ParseTupleAndKeywords()</code></a> is not used, since the latter already does this check.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_Parse">
<code>int PyArg_Parse(PyObject *args, const char *format, ...)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Function used to deconstruct the argument lists of “old-style” functions — these are functions which use the <code>METH_OLDARGS</code> parameter parsing method, which has been removed in Python 3. This is not recommended for use in parameter parsing in new code, and most code in the standard interpreter has been modified to no longer use this for that purpose. It does remain a convenient way to decompose other tuples, however, and may continue to be used for that purpose.</p> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.PyArg_UnpackTuple">
<code>int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)</code> </dt> <dd>
<em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>A simpler form of parameter retrieval which does not use a format string to specify the types of the arguments. Functions which use this method to retrieve their parameters should be declared as <a class="reference internal" href="structures#c.METH_VARARGS" title="METH_VARARGS"><code>METH_VARARGS</code></a> in function or method tables. The tuple containing the actual parameters should be passed as <em>args</em>; it must actually be a tuple. The length of the tuple must be at least <em>min</em> and no more than <em>max</em>; <em>min</em> and <em>max</em> may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a <span class="c-expr sig sig-inline c"><a class="reference internal" href="structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span> variable; these will be filled in with the values from <em>args</em>; they will contain <a class="reference internal" href="../glossary#term-borrowed-reference"><span class="xref std std-term">borrowed references</span></a>. The variables which correspond to optional parameters not given by <em>args</em> will not be filled in; these should be initialized by the caller. This function returns true on success and false if <em>args</em> is not a tuple or contains the wrong number of elements; an exception will be set if there was a failure.</p> <p>This is an example of the use of this function, taken from the sources for the <code>_weakref</code> helper module for weak references:</p> <pre data-language="c">static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
    PyObject *object;
    PyObject *callback = NULL;
    PyObject *result = NULL;

    if (PyArg_UnpackTuple(args, "ref", 1, 2, &amp;object, &amp;callback)) {
        result = PyWeakref_NewRef(object, callback);
    }
    return result;
}
</pre> <p>The call to <a class="reference internal" href="#c.PyArg_UnpackTuple" title="PyArg_UnpackTuple"><code>PyArg_UnpackTuple()</code></a> in this example is entirely equivalent to this call to <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a>:</p> <pre data-language="c">PyArg_ParseTuple(args, "O|O:ref", &amp;object, &amp;callback)
</pre> </dd>
</dl> </section> </section> <section id="building-values"> <h2>Building values</h2> <dl class="c function"> <dt class="sig sig-object c" id="c.Py_BuildValue">
<code>PyObject *Py_BuildValue(const char *format, ...)</code> </dt> <dd>
<em class="refcount">Return value: New reference.</em><em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Create a new value based on a format string similar to those accepted by the <code>PyArg_Parse*</code> family of functions and a sequence of values. Returns the value or <code>NULL</code> in the case of an error; an exception will be raised if <code>NULL</code> is returned.</p> <p><a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a> does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns <code>None</code>; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.</p> <p>When memory buffers are passed as parameters to supply data to build objects, as for the <code>s</code> and <code>s#</code> formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a>. In other words, if your code invokes <code>malloc()</code> and passes the allocated memory to <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a>, your code is responsible for calling <code>free()</code> for that memory once <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a> returns.</p> <p>In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that the format unit will return; and the entry in [square] brackets is the type of the C value(s) to be passed.</p> <p>The characters space, tab, colon and comma are ignored in format strings (but not within format units such as <code>s#</code>). This can be used to make long format strings a tad more readable.</p> <dl class="simple"> <dt>
<code>s (str or None) [const char *]</code> </dt>
<dd>
<p>Convert a null-terminated C string to a Python <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> object using <code>'utf-8'</code> encoding. If the C string pointer is <code>NULL</code>, <code>None</code> is used.</p> </dd> <dt>
<code>s# (str or None) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>Convert a C string and its length to a Python <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> object using <code>'utf-8'</code> encoding. If the C string pointer is <code>NULL</code>, the length is ignored and <code>None</code> is returned.</p> </dd> <dt>
<code>y (bytes) [const char *]</code> </dt>
<dd>
<p>This converts a C string to a Python <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> object. If the C string pointer is <code>NULL</code>, <code>None</code> is returned.</p> </dd> <dt>
<code>y# (bytes) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>This converts a C string and its lengths to a Python object. If the C string pointer is <code>NULL</code>, <code>None</code> is returned.</p> </dd> <dt>
<code>z (str or None) [const char *]</code> </dt>
<dd>
<p>Same as <code>s</code>.</p> </dd> <dt>
<code>z# (str or None) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>Same as <code>s#</code>.</p> </dd> <dt>
<code>u (str) [const wchar_t *]</code> </dt>
<dd>
<p>Convert a null-terminated <code>wchar_t</code> buffer of Unicode (UTF-16 or UCS-4) data to a Python Unicode object. If the Unicode buffer pointer is <code>NULL</code>, <code>None</code> is returned.</p> </dd> <dt>
<code>u# (str) [const wchar_t *, Py_ssize_t]</code> </dt>
<dd>
<p>Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python Unicode object. If the Unicode buffer pointer is <code>NULL</code>, the length is ignored and <code>None</code> is returned.</p> </dd> <dt>
<code>U (str or None) [const char *]</code> </dt>
<dd>
<p>Same as <code>s</code>.</p> </dd> <dt>
<code>U# (str or None) [const char *, Py_ssize_t]</code> </dt>
<dd>
<p>Same as <code>s#</code>.</p> </dd> <dt>
<code>i (int) [int]</code> </dt>
<dd>
<p>Convert a plain C <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> to a Python integer object.</p> </dd> <dt>
<code>b (int) [char]</code> </dt>
<dd>
<p>Convert a plain C <span class="c-expr sig sig-inline c"><span class="kt">char</span></span> to a Python integer object.</p> </dd> <dt>
<code>h (int) [short int]</code> </dt>
<dd>
<p>Convert a plain C <span class="c-expr sig sig-inline c"><span class="kt">short</span><span class="w"> </span><span class="kt">int</span></span> to a Python integer object.</p> </dd> <dt>
<code>l (int) [long int]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">long</span><span class="w"> </span><span class="kt">int</span></span> to a Python integer object.</p> </dd> <dt>
<code>B (int) [unsigned char]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">char</span></span> to a Python integer object.</p> </dd> <dt>
<code>H (int) [unsigned short int]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">short</span><span class="w"> </span><span class="kt">int</span></span> to a Python integer object.</p> </dd> <dt>
<code>I (int) [unsigned int]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span></span> to a Python integer object.</p> </dd> <dt>
<code>k (int) [unsigned long]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span></span> to a Python integer object.</p> </dd> <dt>
<code>L (int) [long long]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span> to a Python integer object.</p> </dd> <dt>
<code>K (int) [unsigned long long]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span> to a Python integer object.</p> </dd> <dt>
<code>n (int) [Py_ssize_t]</code> </dt>
<dd>
<p>Convert a C <a class="reference internal" href="intro#c.Py_ssize_t" title="Py_ssize_t"><code>Py_ssize_t</code></a> to a Python integer.</p> </dd> <dt>
<code>c (bytes of length 1) [char]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> representing a byte to a Python <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> object of length 1.</p> </dd> <dt>
<code>C (str of length 1) [int]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> representing a character to Python <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> object of length 1.</p> </dd> <dt>
<code>d (float) [double]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">double</span></span> to a Python floating point number.</p> </dd> <dt>
<code>f (float) [float]</code> </dt>
<dd>
<p>Convert a C <span class="c-expr sig sig-inline c"><span class="kt">float</span></span> to a Python floating point number.</p> </dd> <dt>
<code>D (complex) [Py_complex *]</code> </dt>
<dd>
<p>Convert a C <a class="reference internal" href="complex#c.Py_complex" title="Py_complex"><code>Py_complex</code></a> structure to a Python complex number.</p> </dd> <dt>
<code>O (object) [PyObject *]</code> </dt>
<dd>
<p>Pass a Python object untouched but create a new <a class="reference internal" href="../glossary#term-strong-reference"><span class="xref std std-term">strong reference</span></a> to it (i.e. its reference count is incremented by one). If the object passed in is a <code>NULL</code> pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a> will return <code>NULL</code> but won’t raise an exception. If no exception has been raised yet, <a class="reference internal" href="../library/exceptions#SystemError" title="SystemError"><code>SystemError</code></a> is set.</p> </dd> <dt>
<code>S (object) [PyObject *]</code> </dt>
<dd>
<p>Same as <code>O</code>.</p> </dd> <dt>
<code>N (object) [PyObject *]</code> </dt>
<dd>
<p>Same as <code>O</code>, except it doesn’t create a new <a class="reference internal" href="../glossary#term-strong-reference"><span class="xref std std-term">strong reference</span></a>. Useful when the object is created by a call to an object constructor in the argument list.</p> </dd> <dt>
<code>O&amp; (object) [converter, anything]</code> </dt>
<dd>
<p>Convert <em>anything</em> to a Python object through a <em>converter</em> function. The function is called with <em>anything</em> (which should be compatible with <span class="c-expr sig sig-inline c"><span class="kt">void</span><span class="p">*</span></span>) as its argument and should return a “new” Python object, or <code>NULL</code> if an error occurred.</p> </dd> <dt>
<code>(items) (tuple) [matching-items]</code> </dt>
<dd>
<p>Convert a sequence of C values to a Python tuple with the same number of items.</p> </dd> <dt>
<code>[items] (list) [matching-items]</code> </dt>
<dd>
<p>Convert a sequence of C values to a Python list with the same number of items.</p> </dd> <dt>
<code>{items} (dict) [matching-items]</code> </dt>
<dd>
<p>Convert a sequence of C values to a Python dictionary. Each pair of consecutive C values adds one item to the dictionary, serving as key and value, respectively.</p> </dd> </dl> <p>If there is an error in the format string, the <a class="reference internal" href="../library/exceptions#SystemError" title="SystemError"><code>SystemError</code></a> exception is set and <code>NULL</code> returned.</p> </dd>
</dl> <dl class="c function"> <dt class="sig sig-object c" id="c.Py_VaBuildValue">
<code>PyObject *Py_VaBuildValue(const char *format, va_list vargs)</code> </dt> <dd>
<em class="refcount">Return value: New reference.</em><em class="stableabi"> Part of the <a class="reference internal" href="stable#stable"><span class="std std-ref">Stable ABI</span></a>.</em><p>Identical to <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code>Py_BuildValue()</code></a>, except that it accepts a va_list rather than a variable number of arguments.</p> </dd>
</dl> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/c-api/arg.html" class="_attribution-link">https://docs.python.org/3.12/c-api/arg.html</a>
  </p>
</div>