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