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