blob: 5f82904966d4afbb2549918f1ec404fc758ac682 [file] [log] [blame]
Georg Brandl54a3faa2008-01-20 09:30:57 +00001.. highlightlang:: 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, :cfunc:`PyArg_ParseTuple`,
13:cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`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
17A format string consists of zero or more "format units." A format unit
18describes one Python object; it is usually a single character or a parenthesized
19sequence of format units. With a few exceptions, a format unit that is not a
20parenthesized sequence normally corresponds to a single address argument to
21these functions. In the following description, the quoted form is the format
22unit; the entry in (round) parentheses is the Python object type that matches
23the format unit; and the entry in [square] brackets is the type of the C
24variable(s) whose address should be passed.
25
26``s`` (string or Unicode object) [const char \*]
27 Convert a Python string or Unicode object to a C pointer to a character string.
28 You must not provide storage for the string itself; a pointer to an existing
29 string is stored into the character pointer variable whose address you pass.
30 The C string is NUL-terminated. The Python string must not contain embedded NUL
31 bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are
32 converted to C strings using the default encoding. If this conversion fails, a
33 :exc:`UnicodeError` is raised.
34
35``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int]
36 This variant on ``s`` stores into two C variables, the first one a pointer to a
37 character string, the second one its length. In this case the Python string may
38 contain embedded null bytes. Unicode objects pass back a pointer to the default
39 encoded string version of the object if such a conversion is possible. All
40 other read-buffer compatible objects pass back a reference to the raw internal
41 data representation.
42
43``y`` (bytes object) [const char \*]
44 This variant on ``s`` convert a Python bytes object to a C pointer to a
45 character string. The bytes object must not contain embedded NUL bytes; if it
46 does, a :exc:`TypeError` exception is raised.
47
48``y#`` (bytes object) [const char \*, int]
49 This variant on ``s#`` stores into two C variables, the first one a pointer to a
50 character string, the second one its length. This only accepts bytes objects.
51
52``z`` (string or ``None``) [const char \*]
53 Like ``s``, but the Python object may also be ``None``, in which case the C
54 pointer is set to *NULL*.
55
56``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int]
57 This is to ``s#`` as ``z`` is to ``s``.
58
59``u`` (Unicode object) [Py_UNICODE \*]
60 Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of
61 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide
62 storage for the Unicode data buffer; a pointer to the existing Unicode data is
63 stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass.
64
65``u#`` (Unicode object) [Py_UNICODE \*, int]
66 This variant on ``u`` stores into two C variables, the first one a pointer to a
67 Unicode data buffer, the second one its length. Non-Unicode objects are handled
68 by interpreting their read-buffer pointer as pointer to a :ctype:`Py_UNICODE`
69 array.
70
71``Z`` (Unicode or ``None``) [Py_UNICODE \*]
72 Like ``s``, but the Python object may also be ``None``, in which case the C
73 pointer is set to *NULL*.
74
75``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int]
76 This is to ``u#`` as ``Z`` is to ``u``.
77
78``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
79 This variant on ``s`` is used for encoding Unicode and objects convertible to
80 Unicode into a character buffer. It only works for encoded data without embedded
81 NUL bytes.
82
83 This format requires two arguments. The first is only used as input, and
84 must be a :ctype:`const char\*` which points to the name of an encoding as a
85 NUL-terminated string, or *NULL*, in which case the default encoding is used.
86 An exception is raised if the named encoding is not known to Python. The
87 second argument must be a :ctype:`char\*\*`; the value of the pointer it
88 references will be set to a buffer with the contents of the argument text.
89 The text will be encoded in the encoding specified by the first argument.
90
91 :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the
92 encoded data into this buffer and adjust *\*buffer* to reference the newly
93 allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to
94 free the allocated buffer after use.
95
96``et`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
97 Same as ``es`` except that 8-bit string objects are passed through without
98 recoding them. Instead, the implementation assumes that the string object uses
99 the encoding passed in as parameter.
100
101``es#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
102 This variant on ``s#`` is used for encoding Unicode and objects convertible to
103 Unicode into a character buffer. Unlike the ``es`` format, this variant allows
104 input data which contains NUL characters.
105
106 It requires three arguments. The first is only used as input, and must be a
107 :ctype:`const char\*` which points to the name of an encoding as a
108 NUL-terminated string, or *NULL*, in which case the default encoding is used.
109 An exception is raised if the named encoding is not known to Python. The
110 second argument must be a :ctype:`char\*\*`; the value of the pointer it
111 references will be set to a buffer with the contents of the argument text.
112 The text will be encoded in the encoding specified by the first argument.
113 The third argument must be a pointer to an integer; the referenced integer
114 will be set to the number of bytes in the output buffer.
115
116 There are two modes of operation:
117
118 If *\*buffer* points a *NULL* pointer, the function will allocate a buffer of
119 the needed size, copy the encoded data into this buffer and set *\*buffer* to
120 reference the newly allocated storage. The caller is responsible for calling
121 :cfunc:`PyMem_Free` to free the allocated buffer after usage.
122
123 If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer),
124 :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the
125 initial value of *\*buffer_length* as the buffer size. It will then copy the
126 encoded data into the buffer and NUL-terminate it. If the buffer is not large
127 enough, a :exc:`ValueError` will be set.
128
129 In both cases, *\*buffer_length* is set to the length of the encoded data
130 without the trailing NUL byte.
131
132``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
133 Same as ``es#`` except that string objects are passed through without recoding
134 them. Instead, the implementation assumes that the string object uses the
135 encoding passed in as parameter.
136
137``b`` (integer) [char]
138 Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
139
140``B`` (integer) [unsigned char]
141 Convert a Python integer to a tiny int without overflow checking, stored in a C
142 :ctype:`unsigned char`.
143
144``h`` (integer) [short int]
145 Convert a Python integer to a C :ctype:`short int`.
146
147``H`` (integer) [unsigned short int]
148 Convert a Python integer to a C :ctype:`unsigned short int`, without overflow
149 checking.
150
151``i`` (integer) [int]
152 Convert a Python integer to a plain C :ctype:`int`.
153
154``I`` (integer) [unsigned int]
155 Convert a Python integer to a C :ctype:`unsigned int`, without overflow
156 checking.
157
158``l`` (integer) [long int]
159 Convert a Python integer to a C :ctype:`long int`.
160
161``k`` (integer) [unsigned long]
162 Convert a Python integer to a C :ctype:`unsigned long` without
163 overflow checking.
164
165``L`` (integer) [PY_LONG_LONG]
166 Convert a Python integer to a C :ctype:`long long`. This format is only
167 available on platforms that support :ctype:`long long` (or :ctype:`_int64` on
168 Windows).
169
170``K`` (integer) [unsigned PY_LONG_LONG]
171 Convert a Python integer to a C :ctype:`unsigned long long`
172 without overflow checking. This format is only available on platforms that
173 support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows).
174
175``n`` (integer) [Py_ssize_t]
176 Convert a Python integer to a C :ctype:`Py_ssize_t`.
177
178``c`` (string of length 1) [char]
179 Convert a Python character, represented as a string of length 1, to a C
180 :ctype:`char`.
181
182``f`` (float) [float]
183 Convert a Python floating point number to a C :ctype:`float`.
184
185``d`` (float) [double]
186 Convert a Python floating point number to a C :ctype:`double`.
187
188``D`` (complex) [Py_complex]
189 Convert a Python complex number to a C :ctype:`Py_complex` structure.
190
191``O`` (object) [PyObject \*]
192 Store a Python object (without any conversion) in a C object pointer. The C
193 program thus receives the actual object that was passed. The object's reference
194 count is not increased. The pointer stored is not *NULL*.
195
196``O!`` (object) [*typeobject*, PyObject \*]
197 Store a Python object in a C object pointer. This is similar to ``O``, but
198 takes two C arguments: the first is the address of a Python type object, the
199 second is the address of the C variable (of type :ctype:`PyObject\*`) into which
200 the object pointer is stored. If the Python object does not have the required
201 type, :exc:`TypeError` is raised.
202
203``O&`` (object) [*converter*, *anything*]
204 Convert a Python object to a C variable through a *converter* function. This
205 takes two arguments: the first is a function, the second is the address of a C
206 variable (of arbitrary type), converted to :ctype:`void \*`. The *converter*
207 function in turn is called as follows::
208
209 status = converter(object, address);
210
211 where *object* is the Python object to be converted and *address* is the
212 :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function.
213 The returned *status* should be ``1`` for a successful conversion and ``0`` if
214 the conversion has failed. When the conversion fails, the *converter* function
215 should raise an exception.
216
217``S`` (string) [PyStringObject \*]
218 Like ``O`` but requires that the Python object is a string object. Raises
219 :exc:`TypeError` if the object is not a string object. The C variable may also
220 be declared as :ctype:`PyObject\*`.
221
222``U`` (Unicode string) [PyUnicodeObject \*]
223 Like ``O`` but requires that the Python object is a Unicode object. Raises
224 :exc:`TypeError` if the object is not a Unicode object. The C variable may also
225 be declared as :ctype:`PyObject\*`.
226
227``t#`` (read-only character buffer) [char \*, int]
228 Like ``s#``, but accepts any object which implements the read-only buffer
229 interface. The :ctype:`char\*` variable is set to point to the first byte of
230 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
231 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
232 others.
233
234``w`` (read-write character buffer) [char \*]
235 Similar to ``s``, but accepts any object which implements the read-write buffer
236 interface. The caller must determine the length of the buffer by other means,
237 or use ``w#`` instead. Only single-segment buffer objects are accepted;
238 :exc:`TypeError` is raised for all others.
239
240``w#`` (read-write character buffer) [char \*, int]
241 Like ``s#``, but accepts any object which implements the read-write buffer
242 interface. The :ctype:`char \*` variable is set to point to the first byte of
243 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
244 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
245 others.
246
247``(items)`` (tuple) [*matching-items*]
248 The object must be a Python sequence whose length is the number of format units
249 in *items*. The C arguments must correspond to the individual format units in
250 *items*. Format units for sequences may be nested.
251
252It is possible to pass "long" integers (integers whose value exceeds the
253platform's :const:`LONG_MAX`) however no proper range checking is done --- the
254most significant bits are silently truncated when the receiving field is too
255small to receive the value (actually, the semantics are inherited from downcasts
256in C --- your mileage may vary).
257
258A few other characters have a meaning in a format string. These may not occur
259inside nested parentheses. They are:
260
261``|``
262 Indicates that the remaining arguments in the Python argument list are optional.
263 The C variables corresponding to optional arguments should be initialized to
264 their default value --- when an optional argument is not specified,
265 :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C
266 variable(s).
267
268``:``
269 The list of format units ends here; the string after the colon is used as the
270 function name in error messages (the "associated value" of the exception that
271 :cfunc:`PyArg_ParseTuple` raises).
272
273``;``
274 The list of format units ends here; the string after the semicolon is used as
275 the error message *instead* of the default error message. Clearly, ``:`` and
276 ``;`` mutually exclude each other.
277
278Note that any Python object references which are provided to the caller are
279*borrowed* references; do not decrement their reference count!
280
281Additional arguments passed to these functions must be addresses of variables
282whose type is determined by the format string; these are used to store values
283from the input tuple. There are a few cases, as described in the list of format
284units above, where these parameters are used as input values; they should match
285what is specified for the corresponding format unit in that case.
286
287For the conversion to succeed, the *arg* object must match the format and the
288format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions
289return true, otherwise they return false and raise an appropriate exception.
290
291
292.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
293
294 Parse the parameters of a function that takes only positional parameters into
295 local variables. Returns true on success; on failure, it returns false and
296 raises the appropriate exception.
297
298
299.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
300
301 Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather
302 than a variable number of arguments.
303
304
305.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
306
307 Parse the parameters of a function that takes both positional and keyword
308 parameters into local variables. Returns true on success; on failure, it
309 returns false and raises the appropriate exception.
310
311
312.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
313
314 Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a
315 va_list rather than a variable number of arguments.
316
317
318.. XXX deprecated, will be removed
319.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...)
320
321 Function used to deconstruct the argument lists of "old-style" functions ---
322 these are functions which use the :const:`METH_OLDARGS` parameter parsing
323 method. This is not recommended for use in parameter parsing in new code, and
324 most code in the standard interpreter has been modified to no longer use this
325 for that purpose. It does remain a convenient way to decompose other tuples,
326 however, and may continue to be used for that purpose.
327
328
329.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
330
331 A simpler form of parameter retrieval which does not use a format string to
332 specify the types of the arguments. Functions which use this method to retrieve
333 their parameters should be declared as :const:`METH_VARARGS` in function or
334 method tables. The tuple containing the actual parameters should be passed as
335 *args*; it must actually be a tuple. The length of the tuple must be at least
336 *min* and no more than *max*; *min* and *max* may be equal. Additional
337 arguments must be passed to the function, each of which should be a pointer to a
338 :ctype:`PyObject\*` variable; these will be filled in with the values from
339 *args*; they will contain borrowed references. The variables which correspond
340 to optional parameters not given by *args* will not be filled in; these should
341 be initialized by the caller. This function returns true on success and false if
342 *args* is not a tuple or contains the wrong number of elements; an exception
343 will be set if there was a failure.
344
345 This is an example of the use of this function, taken from the sources for the
346 :mod:`_weakref` helper module for weak references::
347
348 static PyObject *
349 weakref_ref(PyObject *self, PyObject *args)
350 {
351 PyObject *object;
352 PyObject *callback = NULL;
353 PyObject *result = NULL;
354
355 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
356 result = PyWeakref_NewRef(object, callback);
357 }
358 return result;
359 }
360
361 The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to
362 this call to :cfunc:`PyArg_ParseTuple`::
363
364 PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
365
366
367.. cfunction:: PyObject* Py_BuildValue(const char *format, ...)
368
369 Create a new value based on a format string similar to those accepted by the
370 :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. Returns
371 the value or *NULL* in the case of an error; an exception will be raised if
372 *NULL* is returned.
373
374 :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple only if
375 its format string contains two or more format units. If the format string is
376 empty, it returns ``None``; if it contains exactly one format unit, it returns
377 whatever object is described by that format unit. To force it to return a tuple
378 of size 0 or one, parenthesize the format string.
379
380 When memory buffers are passed as parameters to supply data to build objects, as
381 for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided
382 by the caller are never referenced by the objects created by
383 :cfunc:`Py_BuildValue`. In other words, if your code invokes :cfunc:`malloc`
384 and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is
385 responsible for calling :cfunc:`free` for that memory once
386 :cfunc:`Py_BuildValue` returns.
387
388 In the following description, the quoted form is the format unit; the entry in
389 (round) parentheses is the Python object type that the format unit will return;
390 and the entry in [square] brackets is the type of the C value(s) to be passed.
391
392 The characters space, tab, colon and comma are ignored in format strings (but
393 not within format units such as ``s#``). This can be used to make long format
394 strings a tad more readable.
395
396 ``s`` (string) [char \*]
397 Convert a null-terminated C string to a Python object. If the C string pointer
398 is *NULL*, ``None`` is used.
399
400 ``s#`` (string) [char \*, int]
401 Convert a C string and its length to a Python object. If the C string pointer
402 is *NULL*, the length is ignored and ``None`` is returned.
403
404 ``z`` (string or ``None``) [char \*]
405 Same as ``s``.
406
407 ``z#`` (string or ``None``) [char \*, int]
408 Same as ``s#``.
409
410 ``u`` (Unicode string) [Py_UNICODE \*]
411 Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python
412 Unicode object. If the Unicode buffer pointer is *NULL*, ``None`` is returned.
413
414 ``u#`` (Unicode string) [Py_UNICODE \*, int]
415 Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python
416 Unicode object. If the Unicode buffer pointer is *NULL*, the length is ignored
417 and ``None`` is returned.
418
419 ``U`` (string) [char \*]
420 Convert a null-terminated C string to a Python unicode object. If the C string
421 pointer is *NULL*, ``None`` is used.
422
423 ``U#`` (string) [char \*, int]
424 Convert a C string and its length to a Python unicode object. If the C string
425 pointer is *NULL*, the length is ignored and ``None`` is returned.
426
427 ``i`` (integer) [int]
428 Convert a plain C :ctype:`int` to a Python integer object.
429
430 ``b`` (integer) [char]
431 Convert a plain C :ctype:`char` to a Python integer object.
432
433 ``h`` (integer) [short int]
434 Convert a plain C :ctype:`short int` to a Python integer object.
435
436 ``l`` (integer) [long int]
437 Convert a C :ctype:`long int` to a Python integer object.
438
439 ``B`` (integer) [unsigned char]
440 Convert a C :ctype:`unsigned char` to a Python integer object.
441
442 ``H`` (integer) [unsigned short int]
443 Convert a C :ctype:`unsigned short int` to a Python integer object.
444
445 ``I`` (integer/long) [unsigned int]
446 Convert a C :ctype:`unsigned int` to a Python long integer object.
447
448 ``k`` (integer/long) [unsigned long]
449 Convert a C :ctype:`unsigned long` to a Python long integer object.
450
451 ``L`` (long) [PY_LONG_LONG]
452 Convert a C :ctype:`long long` to a Python integer object. Only available
453 on platforms that support :ctype:`long long`.
454
455 ``K`` (long) [unsigned PY_LONG_LONG]
456 Convert a C :ctype:`unsigned long long` to a Python integer object. Only
457 available on platforms that support :ctype:`unsigned long long`.
458
459 ``n`` (int) [Py_ssize_t]
460 Convert a C :ctype:`Py_ssize_t` to a Python integer.
461
462 ``c`` (string of length 1) [char]
463 Convert a C :ctype:`int` representing a character to a Python string of length
464 1.
465
466 ``d`` (float) [double]
467 Convert a C :ctype:`double` to a Python floating point number.
468
469 ``f`` (float) [float]
470 Same as ``d``.
471
472 ``D`` (complex) [Py_complex \*]
473 Convert a C :ctype:`Py_complex` structure to a Python complex number.
474
475 ``O`` (object) [PyObject \*]
476 Pass a Python object untouched (except for its reference count, which is
477 incremented by one). If the object passed in is a *NULL* pointer, it is assumed
478 that this was caused because the call producing the argument found an error and
479 set an exception. Therefore, :cfunc:`Py_BuildValue` will return *NULL* but won't
480 raise an exception. If no exception has been raised yet, :exc:`SystemError` is
481 set.
482
483 ``S`` (object) [PyObject \*]
484 Same as ``O``.
485
486 ``N`` (object) [PyObject \*]
487 Same as ``O``, except it doesn't increment the reference count on the object.
488 Useful when the object is created by a call to an object constructor in the
489 argument list.
490
491 ``O&`` (object) [*converter*, *anything*]
492 Convert *anything* to a Python object through a *converter* function. The
493 function is called with *anything* (which should be compatible with :ctype:`void
494 \*`) as its argument and should return a "new" Python object, or *NULL* if an
495 error occurred.
496
497 ``(items)`` (tuple) [*matching-items*]
498 Convert a sequence of C values to a Python tuple with the same number of items.
499
500 ``[items]`` (list) [*matching-items*]
501 Convert a sequence of C values to a Python list with the same number of items.
502
503 ``{items}`` (dictionary) [*matching-items*]
504 Convert a sequence of C values to a Python dictionary. Each pair of consecutive
505 C values adds one item to the dictionary, serving as key and value,
506 respectively.
507
508 If there is an error in the format string, the :exc:`SystemError` exception is
509 set and *NULL* returned.