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