Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | .. highlightlang:: c |
| 2 | |
| 3 | |
| 4 | .. _utilities: |
| 5 | |
| 6 | ********* |
| 7 | Utilities |
| 8 | ********* |
| 9 | |
| 10 | The functions in this chapter perform various utility tasks, ranging from |
| 11 | helping C code be more portable across platforms, using Python modules from C, |
| 12 | and parsing function arguments and constructing Python values from C values. |
| 13 | |
| 14 | |
| 15 | .. _os: |
| 16 | |
| 17 | Operating System Utilities |
| 18 | ========================== |
| 19 | |
| 20 | |
| 21 | .. cfunction:: int Py_FdIsInteractive(FILE *fp, const char *filename) |
| 22 | |
| 23 | Return true (nonzero) if the standard I/O file *fp* with name *filename* is |
| 24 | deemed interactive. This is the case for files for which ``isatty(fileno(fp))`` |
| 25 | is true. If the global flag :cdata:`Py_InteractiveFlag` is true, this function |
| 26 | also returns true if the *filename* pointer is *NULL* or if the name is equal to |
| 27 | one of the strings ``'<stdin>'`` or ``'???'``. |
| 28 | |
| 29 | |
| 30 | .. cfunction:: long PyOS_GetLastModificationTime(char *filename) |
| 31 | |
| 32 | Return the time of last modification of the file *filename*. The result is |
| 33 | encoded in the same way as the timestamp returned by the standard C library |
| 34 | function :cfunc:`time`. |
| 35 | |
| 36 | |
| 37 | .. cfunction:: void PyOS_AfterFork() |
| 38 | |
| 39 | Function to update some internal state after a process fork; this should be |
| 40 | called in the new process if the Python interpreter will continue to be used. |
| 41 | If a new executable is loaded into the new process, this function does not need |
| 42 | to be called. |
| 43 | |
| 44 | |
| 45 | .. cfunction:: int PyOS_CheckStack() |
| 46 | |
| 47 | Return true when the interpreter runs out of stack space. This is a reliable |
| 48 | check, but is only available when :const:`USE_STACKCHECK` is defined (currently |
| 49 | on Windows using the Microsoft Visual C++ compiler). :const:`USE_STACKCHECK` |
| 50 | will be defined automatically; you should never change the definition in your |
| 51 | own code. |
| 52 | |
| 53 | |
| 54 | .. cfunction:: PyOS_sighandler_t PyOS_getsig(int i) |
| 55 | |
| 56 | Return the current signal handler for signal *i*. This is a thin wrapper around |
| 57 | either :cfunc:`sigaction` or :cfunc:`signal`. Do not call those functions |
| 58 | directly! :ctype:`PyOS_sighandler_t` is a typedef alias for :ctype:`void |
| 59 | (\*)(int)`. |
| 60 | |
| 61 | |
| 62 | .. cfunction:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) |
| 63 | |
| 64 | Set the signal handler for signal *i* to be *h*; return the old signal handler. |
| 65 | This is a thin wrapper around either :cfunc:`sigaction` or :cfunc:`signal`. Do |
| 66 | not call those functions directly! :ctype:`PyOS_sighandler_t` is a typedef |
| 67 | alias for :ctype:`void (\*)(int)`. |
| 68 | |
| 69 | |
| 70 | .. _processcontrol: |
| 71 | |
| 72 | Process Control |
| 73 | =============== |
| 74 | |
| 75 | |
| 76 | .. cfunction:: void Py_FatalError(const char *message) |
| 77 | |
| 78 | .. index:: single: abort() |
| 79 | |
| 80 | Print a fatal error message and kill the process. No cleanup is performed. |
| 81 | This function should only be invoked when a condition is detected that would |
| 82 | make it dangerous to continue using the Python interpreter; e.g., when the |
| 83 | object administration appears to be corrupted. On Unix, the standard C library |
| 84 | function :cfunc:`abort` is called which will attempt to produce a :file:`core` |
| 85 | file. |
| 86 | |
| 87 | |
| 88 | .. cfunction:: void Py_Exit(int status) |
| 89 | |
| 90 | .. index:: |
| 91 | single: Py_Finalize() |
| 92 | single: exit() |
| 93 | |
| 94 | Exit the current process. This calls :cfunc:`Py_Finalize` and then calls the |
| 95 | standard C library function ``exit(status)``. |
| 96 | |
| 97 | |
| 98 | .. cfunction:: int Py_AtExit(void (*func) ()) |
| 99 | |
| 100 | .. index:: |
| 101 | single: Py_Finalize() |
| 102 | single: cleanup functions |
| 103 | |
| 104 | Register a cleanup function to be called by :cfunc:`Py_Finalize`. The cleanup |
| 105 | function will be called with no arguments and should return no value. At most |
| 106 | 32 cleanup functions can be registered. When the registration is successful, |
| 107 | :cfunc:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup |
| 108 | function registered last is called first. Each cleanup function will be called |
| 109 | at most once. Since Python's internal finalization will have completed before |
| 110 | the cleanup function, no Python APIs should be called by *func*. |
| 111 | |
| 112 | |
| 113 | .. _importing: |
| 114 | |
| 115 | Importing Modules |
| 116 | ================= |
| 117 | |
| 118 | |
| 119 | .. cfunction:: PyObject* PyImport_ImportModule(const char *name) |
| 120 | |
| 121 | .. index:: |
| 122 | single: package variable; __all__ |
| 123 | single: __all__ (package variable) |
| 124 | |
| 125 | This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below, |
| 126 | leaving the *globals* and *locals* arguments set to *NULL*. When the *name* |
| 127 | argument contains a dot (when it specifies a submodule of a package), the |
| 128 | *fromlist* argument is set to the list ``['*']`` so that the return value is the |
| 129 | named module rather than the top-level package containing it as would otherwise |
| 130 | be the case. (Unfortunately, this has an additional side effect when *name* in |
| 131 | fact specifies a subpackage instead of a submodule: the submodules specified in |
| 132 | the package's ``__all__`` variable are loaded.) Return a new reference to the |
| 133 | imported module, or *NULL* with an exception set on failure. Before Python 2.4, |
| 134 | the module may still be created in the failure case --- examine ``sys.modules`` |
| 135 | to find out. Starting with Python 2.4, a failing import of a module no longer |
| 136 | leaves the module in ``sys.modules``. |
| 137 | |
| 138 | .. versionchanged:: 2.4 |
| 139 | failing imports remove incomplete module objects. |
| 140 | |
| 141 | .. index:: single: modules (in module sys) |
| 142 | |
| 143 | |
| 144 | .. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) |
| 145 | |
| 146 | .. index:: builtin: __import__ |
| 147 | |
| 148 | Import a module. This is best described by referring to the built-in Python |
| 149 | function :func:`__import__`, as the standard :func:`__import__` function calls |
| 150 | this function directly. |
| 151 | |
| 152 | The return value is a new reference to the imported module or top-level package, |
| 153 | or *NULL* with an exception set on failure (before Python 2.4, the module may |
| 154 | still be created in this case). Like for :func:`__import__`, the return value |
| 155 | when a submodule of a package was requested is normally the top-level package, |
| 156 | unless a non-empty *fromlist* was given. |
| 157 | |
| 158 | .. versionchanged:: 2.4 |
| 159 | failing imports remove incomplete module objects. |
| 160 | |
| 161 | |
| 162 | .. cfunction:: PyObject* PyImport_Import(PyObject *name) |
| 163 | |
| 164 | .. index:: |
| 165 | module: rexec |
| 166 | module: ihooks |
| 167 | |
| 168 | This is a higher-level interface that calls the current "import hook function". |
| 169 | It invokes the :func:`__import__` function from the ``__builtins__`` of the |
| 170 | current globals. This means that the import is done using whatever import hooks |
| 171 | are installed in the current environment, e.g. by :mod:`rexec` or :mod:`ihooks`. |
| 172 | |
| 173 | |
| 174 | .. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m) |
| 175 | |
| 176 | .. index:: builtin: reload |
| 177 | |
| 178 | Reload a module. This is best described by referring to the built-in Python |
| 179 | function :func:`reload`, as the standard :func:`reload` function calls this |
| 180 | function directly. Return a new reference to the reloaded module, or *NULL* |
| 181 | with an exception set on failure (the module still exists in this case). |
| 182 | |
| 183 | |
| 184 | .. cfunction:: PyObject* PyImport_AddModule(const char *name) |
| 185 | |
| 186 | Return the module object corresponding to a module name. The *name* argument |
| 187 | may be of the form ``package.module``. First check the modules dictionary if |
| 188 | there's one there, and if not, create a new one and insert it in the modules |
| 189 | dictionary. Return *NULL* with an exception set on failure. |
| 190 | |
| 191 | .. note:: |
| 192 | |
| 193 | This function does not load or import the module; if the module wasn't already |
| 194 | loaded, you will get an empty module object. Use :cfunc:`PyImport_ImportModule` |
| 195 | or one of its variants to import a module. Package structures implied by a |
| 196 | dotted name for *name* are not created if not already present. |
| 197 | |
| 198 | |
| 199 | .. cfunction:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co) |
| 200 | |
| 201 | .. index:: builtin: compile |
| 202 | |
| 203 | Given a module name (possibly of the form ``package.module``) and a code object |
| 204 | read from a Python bytecode file or obtained from the built-in function |
| 205 | :func:`compile`, load the module. Return a new reference to the module object, |
| 206 | or *NULL* with an exception set if an error occurred. Before Python 2.4, the |
| 207 | module could still be created in error cases. Starting with Python 2.4, *name* |
| 208 | is removed from ``sys.modules`` in error cases, and even if *name* was already |
| 209 | in ``sys.modules`` on entry to :cfunc:`PyImport_ExecCodeModule`. Leaving |
| 210 | incompletely initialized modules in ``sys.modules`` is dangerous, as imports of |
| 211 | such modules have no way to know that the module object is an unknown (and |
| 212 | probably damaged with respect to the module author's intents) state. |
| 213 | |
| 214 | This function will reload the module if it was already imported. See |
| 215 | :cfunc:`PyImport_ReloadModule` for the intended way to reload a module. |
| 216 | |
| 217 | If *name* points to a dotted name of the form ``package.module``, any package |
| 218 | structures not already created will still not be created. |
| 219 | |
| 220 | .. versionchanged:: 2.4 |
| 221 | *name* is removed from ``sys.modules`` in error cases. |
| 222 | |
| 223 | |
| 224 | .. cfunction:: long PyImport_GetMagicNumber() |
| 225 | |
| 226 | Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and |
| 227 | :file:`.pyo` files). The magic number should be present in the first four bytes |
| 228 | of the bytecode file, in little-endian byte order. |
| 229 | |
| 230 | |
| 231 | .. cfunction:: PyObject* PyImport_GetModuleDict() |
| 232 | |
| 233 | Return the dictionary used for the module administration (a.k.a. |
| 234 | ``sys.modules``). Note that this is a per-interpreter variable. |
| 235 | |
| 236 | |
| 237 | .. cfunction:: void _PyImport_Init() |
| 238 | |
| 239 | Initialize the import mechanism. For internal use only. |
| 240 | |
| 241 | |
| 242 | .. cfunction:: void PyImport_Cleanup() |
| 243 | |
| 244 | Empty the module table. For internal use only. |
| 245 | |
| 246 | |
| 247 | .. cfunction:: void _PyImport_Fini() |
| 248 | |
| 249 | Finalize the import mechanism. For internal use only. |
| 250 | |
| 251 | |
| 252 | .. cfunction:: PyObject* _PyImport_FindExtension(char *, char *) |
| 253 | |
| 254 | For internal use only. |
| 255 | |
| 256 | |
| 257 | .. cfunction:: PyObject* _PyImport_FixupExtension(char *, char *) |
| 258 | |
| 259 | For internal use only. |
| 260 | |
| 261 | |
| 262 | .. cfunction:: int PyImport_ImportFrozenModule(char *name) |
| 263 | |
| 264 | Load a frozen module named *name*. Return ``1`` for success, ``0`` if the |
| 265 | module is not found, and ``-1`` with an exception set if the initialization |
| 266 | failed. To access the imported module on a successful load, use |
| 267 | :cfunc:`PyImport_ImportModule`. (Note the misnomer --- this function would |
| 268 | reload the module if it was already imported.) |
| 269 | |
| 270 | |
| 271 | .. ctype:: struct _frozen |
| 272 | |
| 273 | .. index:: single: freeze utility |
| 274 | |
| 275 | This is the structure type definition for frozen module descriptors, as |
| 276 | generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the |
| 277 | Python source distribution). Its definition, found in :file:`Include/import.h`, |
| 278 | is:: |
| 279 | |
| 280 | struct _frozen { |
| 281 | char *name; |
| 282 | unsigned char *code; |
| 283 | int size; |
| 284 | }; |
| 285 | |
| 286 | |
| 287 | .. cvar:: struct _frozen* PyImport_FrozenModules |
| 288 | |
| 289 | This pointer is initialized to point to an array of :ctype:`struct _frozen` |
| 290 | records, terminated by one whose members are all *NULL* or zero. When a frozen |
| 291 | module is imported, it is searched in this table. Third-party code could play |
| 292 | tricks with this to provide a dynamically created collection of frozen modules. |
| 293 | |
| 294 | |
| 295 | .. cfunction:: int PyImport_AppendInittab(char *name, void (*initfunc)(void)) |
| 296 | |
| 297 | Add a single module to the existing table of built-in modules. This is a |
| 298 | convenience wrapper around :cfunc:`PyImport_ExtendInittab`, returning ``-1`` if |
| 299 | the table could not be extended. The new module can be imported by the name |
| 300 | *name*, and uses the function *initfunc* as the initialization function called |
| 301 | on the first attempted import. This should be called before |
| 302 | :cfunc:`Py_Initialize`. |
| 303 | |
| 304 | |
| 305 | .. ctype:: struct _inittab |
| 306 | |
| 307 | Structure describing a single entry in the list of built-in modules. Each of |
| 308 | these structures gives the name and initialization function for a module built |
| 309 | into the interpreter. Programs which embed Python may use an array of these |
| 310 | structures in conjunction with :cfunc:`PyImport_ExtendInittab` to provide |
| 311 | additional built-in modules. The structure is defined in |
| 312 | :file:`Include/import.h` as:: |
| 313 | |
| 314 | struct _inittab { |
| 315 | char *name; |
| 316 | void (*initfunc)(void); |
| 317 | }; |
| 318 | |
| 319 | |
| 320 | .. cfunction:: int PyImport_ExtendInittab(struct _inittab *newtab) |
| 321 | |
| 322 | Add a collection of modules to the table of built-in modules. The *newtab* |
| 323 | array must end with a sentinel entry which contains *NULL* for the :attr:`name` |
| 324 | field; failure to provide the sentinel value can result in a memory fault. |
| 325 | Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to |
| 326 | extend the internal table. In the event of failure, no modules are added to the |
| 327 | internal table. This should be called before :cfunc:`Py_Initialize`. |
| 328 | |
| 329 | |
| 330 | .. _marshalling-utils: |
| 331 | |
| 332 | Data marshalling support |
| 333 | ======================== |
| 334 | |
| 335 | These routines allow C code to work with serialized objects using the same data |
| 336 | format as the :mod:`marshal` module. There are functions to write data into the |
| 337 | serialization format, and additional functions that can be used to read the data |
| 338 | back. Files used to store marshalled data must be opened in binary mode. |
| 339 | |
| 340 | Numeric values are stored with the least significant byte first. |
| 341 | |
| 342 | The module supports two versions of the data format: version 0 is the historical |
| 343 | version, version 1 (new in Python 2.4) shares interned strings in the file, and |
| 344 | upon unmarshalling. *Py_MARSHAL_VERSION* indicates the current file format |
| 345 | (currently 1). |
| 346 | |
| 347 | |
| 348 | .. cfunction:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) |
| 349 | |
| 350 | Marshal a :ctype:`long` integer, *value*, to *file*. This will only write the |
| 351 | least-significant 32 bits of *value*; regardless of the size of the native |
| 352 | :ctype:`long` type. |
| 353 | |
| 354 | .. versionchanged:: 2.4 |
| 355 | *version* indicates the file format. |
| 356 | |
| 357 | |
| 358 | .. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) |
| 359 | |
| 360 | Marshal a Python object, *value*, to *file*. |
| 361 | |
| 362 | .. versionchanged:: 2.4 |
| 363 | *version* indicates the file format. |
| 364 | |
| 365 | |
| 366 | .. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) |
| 367 | |
| 368 | Return a string object containing the marshalled representation of *value*. |
| 369 | |
| 370 | .. versionchanged:: 2.4 |
| 371 | *version* indicates the file format. |
| 372 | |
| 373 | |
| 374 | The following functions allow marshalled values to be read back in. |
| 375 | |
| 376 | XXX What about error detection? It appears that reading past the end of the |
| 377 | file will always result in a negative numeric value (where that's relevant), but |
| 378 | it's not clear that negative values won't be handled properly when there's no |
| 379 | error. What's the right way to tell? Should only non-negative values be written |
| 380 | using these routines? |
| 381 | |
| 382 | |
| 383 | .. cfunction:: long PyMarshal_ReadLongFromFile(FILE *file) |
| 384 | |
| 385 | Return a C :ctype:`long` from the data stream in a :ctype:`FILE\*` opened for |
| 386 | reading. Only a 32-bit value can be read in using this function, regardless of |
| 387 | the native size of :ctype:`long`. |
| 388 | |
| 389 | |
| 390 | .. cfunction:: int PyMarshal_ReadShortFromFile(FILE *file) |
| 391 | |
| 392 | Return a C :ctype:`short` from the data stream in a :ctype:`FILE\*` opened for |
| 393 | reading. Only a 16-bit value can be read in using this function, regardless of |
| 394 | the native size of :ctype:`short`. |
| 395 | |
| 396 | |
| 397 | .. cfunction:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) |
| 398 | |
| 399 | Return a Python object from the data stream in a :ctype:`FILE\*` opened for |
| 400 | reading. On error, sets the appropriate exception (:exc:`EOFError` or |
| 401 | :exc:`TypeError`) and returns *NULL*. |
| 402 | |
| 403 | |
| 404 | .. cfunction:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) |
| 405 | |
| 406 | Return a Python object from the data stream in a :ctype:`FILE\*` opened for |
| 407 | reading. Unlike :cfunc:`PyMarshal_ReadObjectFromFile`, this function assumes |
| 408 | that no further objects will be read from the file, allowing it to aggressively |
| 409 | load file data into memory so that the de-serialization can operate from data in |
| 410 | memory rather than reading a byte at a time from the file. Only use these |
| 411 | variant if you are certain that you won't be reading anything else from the |
| 412 | file. On error, sets the appropriate exception (:exc:`EOFError` or |
| 413 | :exc:`TypeError`) and returns *NULL*. |
| 414 | |
| 415 | |
| 416 | .. cfunction:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len) |
| 417 | |
| 418 | Return a Python object from the data stream in a character buffer containing |
| 419 | *len* bytes pointed to by *string*. On error, sets the appropriate exception |
| 420 | (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*. |
| 421 | |
| 422 | |
| 423 | .. _arg-parsing: |
| 424 | |
| 425 | Parsing arguments and building values |
| 426 | ===================================== |
| 427 | |
| 428 | These functions are useful when creating your own extensions functions and |
| 429 | methods. Additional information and examples are available in |
| 430 | :ref:`extending-index`. |
| 431 | |
| 432 | The first three of these functions described, :cfunc:`PyArg_ParseTuple`, |
| 433 | :cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use *format |
| 434 | strings* which are used to tell the function about the expected arguments. The |
| 435 | format strings use the same syntax for each of these functions. |
| 436 | |
| 437 | A format string consists of zero or more "format units." A format unit |
| 438 | describes one Python object; it is usually a single character or a parenthesized |
| 439 | sequence of format units. With a few exceptions, a format unit that is not a |
| 440 | parenthesized sequence normally corresponds to a single address argument to |
| 441 | these functions. In the following description, the quoted form is the format |
| 442 | unit; the entry in (round) parentheses is the Python object type that matches |
| 443 | the format unit; and the entry in [square] brackets is the type of the C |
| 444 | variable(s) whose address should be passed. |
| 445 | |
| 446 | ``s`` (string or Unicode object) [const char \*] |
| 447 | Convert a Python string or Unicode object to a C pointer to a character string. |
| 448 | You must not provide storage for the string itself; a pointer to an existing |
| 449 | string is stored into the character pointer variable whose address you pass. |
| 450 | The C string is NUL-terminated. The Python string must not contain embedded NUL |
| 451 | bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are |
| 452 | converted to C strings using the default encoding. If this conversion fails, a |
| 453 | :exc:`UnicodeError` is raised. |
| 454 | |
| 455 | ``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int] |
| 456 | This variant on ``s`` stores into two C variables, the first one a pointer to a |
| 457 | character string, the second one its length. In this case the Python string may |
| 458 | contain embedded null bytes. Unicode objects pass back a pointer to the default |
| 459 | encoded string version of the object if such a conversion is possible. All |
| 460 | other read-buffer compatible objects pass back a reference to the raw internal |
| 461 | data representation. |
| 462 | |
| 463 | ``z`` (string or ``None``) [const char \*] |
| 464 | Like ``s``, but the Python object may also be ``None``, in which case the C |
| 465 | pointer is set to *NULL*. |
| 466 | |
| 467 | ``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int] |
| 468 | This is to ``s#`` as ``z`` is to ``s``. |
| 469 | |
| 470 | ``u`` (Unicode object) [Py_UNICODE \*] |
| 471 | Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of |
| 472 | 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide |
| 473 | storage for the Unicode data buffer; a pointer to the existing Unicode data is |
| 474 | stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass. |
| 475 | |
| 476 | ``u#`` (Unicode object) [Py_UNICODE \*, int] |
| 477 | This variant on ``u`` stores into two C variables, the first one a pointer to a |
| 478 | Unicode data buffer, the second one its length. Non-Unicode objects are handled |
| 479 | by interpreting their read-buffer pointer as pointer to a :ctype:`Py_UNICODE` |
| 480 | array. |
| 481 | |
| 482 | ``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] |
| 483 | This variant on ``s`` is used for encoding Unicode and objects convertible to |
| 484 | Unicode into a character buffer. It only works for encoded data without embedded |
| 485 | NUL bytes. |
| 486 | |
| 487 | This format requires two arguments. The first is only used as input, and |
| 488 | must be a :ctype:`const char\*` which points to the name of an encoding as a |
| 489 | NUL-terminated string, or *NULL*, in which case the default encoding is used. |
| 490 | An exception is raised if the named encoding is not known to Python. The |
| 491 | second argument must be a :ctype:`char\*\*`; the value of the pointer it |
| 492 | references will be set to a buffer with the contents of the argument text. |
| 493 | The text will be encoded in the encoding specified by the first argument. |
| 494 | |
| 495 | :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the |
| 496 | encoded data into this buffer and adjust *\*buffer* to reference the newly |
| 497 | allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to |
| 498 | free the allocated buffer after use. |
| 499 | |
| 500 | ``et`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] |
| 501 | Same as ``es`` except that 8-bit string objects are passed through without |
| 502 | recoding them. Instead, the implementation assumes that the string object uses |
| 503 | the encoding passed in as parameter. |
| 504 | |
| 505 | ``es#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length] |
| 506 | This variant on ``s#`` is used for encoding Unicode and objects convertible to |
| 507 | Unicode into a character buffer. Unlike the ``es`` format, this variant allows |
| 508 | input data which contains NUL characters. |
| 509 | |
| 510 | It requires three arguments. The first is only used as input, and must be a |
| 511 | :ctype:`const char\*` which points to the name of an encoding as a |
| 512 | NUL-terminated string, or *NULL*, in which case the default encoding is used. |
| 513 | An exception is raised if the named encoding is not known to Python. The |
| 514 | second argument must be a :ctype:`char\*\*`; the value of the pointer it |
| 515 | references will be set to a buffer with the contents of the argument text. |
| 516 | The text will be encoded in the encoding specified by the first argument. |
| 517 | The third argument must be a pointer to an integer; the referenced integer |
| 518 | will be set to the number of bytes in the output buffer. |
| 519 | |
| 520 | There are two modes of operation: |
| 521 | |
| 522 | If *\*buffer* points a *NULL* pointer, the function will allocate a buffer of |
| 523 | the needed size, copy the encoded data into this buffer and set *\*buffer* to |
| 524 | reference the newly allocated storage. The caller is responsible for calling |
| 525 | :cfunc:`PyMem_Free` to free the allocated buffer after usage. |
| 526 | |
| 527 | If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer), |
| 528 | :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the |
| 529 | initial value of *\*buffer_length* as the buffer size. It will then copy the |
| 530 | encoded data into the buffer and NUL-terminate it. If the buffer is not large |
| 531 | enough, a :exc:`ValueError` will be set. |
| 532 | |
| 533 | In both cases, *\*buffer_length* is set to the length of the encoded data |
| 534 | without the trailing NUL byte. |
| 535 | |
| 536 | ``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] |
| 537 | Same as ``es#`` except that string objects are passed through without recoding |
| 538 | them. Instead, the implementation assumes that the string object uses the |
| 539 | encoding passed in as parameter. |
| 540 | |
| 541 | ``b`` (integer) [char] |
| 542 | Convert a Python integer to a tiny int, stored in a C :ctype:`char`. |
| 543 | |
| 544 | ``B`` (integer) [unsigned char] |
| 545 | Convert a Python integer to a tiny int without overflow checking, stored in a C |
| 546 | :ctype:`unsigned char`. |
| 547 | |
| 548 | .. versionadded:: 2.3 |
| 549 | |
| 550 | ``h`` (integer) [short int] |
| 551 | Convert a Python integer to a C :ctype:`short int`. |
| 552 | |
| 553 | ``H`` (integer) [unsigned short int] |
| 554 | Convert a Python integer to a C :ctype:`unsigned short int`, without overflow |
| 555 | checking. |
| 556 | |
| 557 | .. versionadded:: 2.3 |
| 558 | |
| 559 | ``i`` (integer) [int] |
| 560 | Convert a Python integer to a plain C :ctype:`int`. |
| 561 | |
| 562 | ``I`` (integer) [unsigned int] |
| 563 | Convert a Python integer to a C :ctype:`unsigned int`, without overflow |
| 564 | checking. |
| 565 | |
| 566 | .. versionadded:: 2.3 |
| 567 | |
| 568 | ``l`` (integer) [long int] |
| 569 | Convert a Python integer to a C :ctype:`long int`. |
| 570 | |
| 571 | ``k`` (integer) [unsigned long] |
| 572 | Convert a Python integer or long integer to a C :ctype:`unsigned long` without |
| 573 | overflow checking. |
| 574 | |
| 575 | .. versionadded:: 2.3 |
| 576 | |
| 577 | ``L`` (integer) [PY_LONG_LONG] |
| 578 | Convert a Python integer to a C :ctype:`long long`. This format is only |
| 579 | available on platforms that support :ctype:`long long` (or :ctype:`_int64` on |
| 580 | Windows). |
| 581 | |
| 582 | ``K`` (integer) [unsigned PY_LONG_LONG] |
| 583 | Convert a Python integer or long integer to a C :ctype:`unsigned long long` |
| 584 | without overflow checking. This format is only available on platforms that |
| 585 | support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows). |
| 586 | |
| 587 | .. versionadded:: 2.3 |
| 588 | |
| 589 | ``n`` (integer) [Py_ssize_t] |
| 590 | Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`. |
| 591 | |
| 592 | .. versionadded:: 2.5 |
| 593 | |
| 594 | ``c`` (string of length 1) [char] |
| 595 | Convert a Python character, represented as a string of length 1, to a C |
| 596 | :ctype:`char`. |
| 597 | |
| 598 | ``f`` (float) [float] |
| 599 | Convert a Python floating point number to a C :ctype:`float`. |
| 600 | |
| 601 | ``d`` (float) [double] |
| 602 | Convert a Python floating point number to a C :ctype:`double`. |
| 603 | |
| 604 | ``D`` (complex) [Py_complex] |
| 605 | Convert a Python complex number to a C :ctype:`Py_complex` structure. |
| 606 | |
| 607 | ``O`` (object) [PyObject \*] |
| 608 | Store a Python object (without any conversion) in a C object pointer. The C |
| 609 | program thus receives the actual object that was passed. The object's reference |
| 610 | count is not increased. The pointer stored is not *NULL*. |
| 611 | |
| 612 | ``O!`` (object) [*typeobject*, PyObject \*] |
| 613 | Store a Python object in a C object pointer. This is similar to ``O``, but |
| 614 | takes two C arguments: the first is the address of a Python type object, the |
| 615 | second is the address of the C variable (of type :ctype:`PyObject\*`) into which |
| 616 | the object pointer is stored. If the Python object does not have the required |
| 617 | type, :exc:`TypeError` is raised. |
| 618 | |
| 619 | ``O&`` (object) [*converter*, *anything*] |
| 620 | Convert a Python object to a C variable through a *converter* function. This |
| 621 | takes two arguments: the first is a function, the second is the address of a C |
| 622 | variable (of arbitrary type), converted to :ctype:`void \*`. The *converter* |
| 623 | function in turn is called as follows:: |
| 624 | |
| 625 | status = converter(object, address); |
| 626 | |
| 627 | where *object* is the Python object to be converted and *address* is the |
| 628 | :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function. |
| 629 | The returned *status* should be ``1`` for a successful conversion and ``0`` if |
| 630 | the conversion has failed. When the conversion fails, the *converter* function |
| 631 | should raise an exception. |
| 632 | |
| 633 | ``S`` (string) [PyStringObject \*] |
| 634 | Like ``O`` but requires that the Python object is a string object. Raises |
| 635 | :exc:`TypeError` if the object is not a string object. The C variable may also |
| 636 | be declared as :ctype:`PyObject\*`. |
| 637 | |
| 638 | ``U`` (Unicode string) [PyUnicodeObject \*] |
| 639 | Like ``O`` but requires that the Python object is a Unicode object. Raises |
| 640 | :exc:`TypeError` if the object is not a Unicode object. The C variable may also |
| 641 | be declared as :ctype:`PyObject\*`. |
| 642 | |
| 643 | ``t#`` (read-only character buffer) [char \*, int] |
| 644 | Like ``s#``, but accepts any object which implements the read-only buffer |
| 645 | interface. The :ctype:`char\*` variable is set to point to the first byte of |
| 646 | the buffer, and the :ctype:`int` is set to the length of the buffer. Only |
| 647 | single-segment buffer objects are accepted; :exc:`TypeError` is raised for all |
| 648 | others. |
| 649 | |
| 650 | ``w`` (read-write character buffer) [char \*] |
| 651 | Similar to ``s``, but accepts any object which implements the read-write buffer |
| 652 | interface. The caller must determine the length of the buffer by other means, |
| 653 | or use ``w#`` instead. Only single-segment buffer objects are accepted; |
| 654 | :exc:`TypeError` is raised for all others. |
| 655 | |
| 656 | ``w#`` (read-write character buffer) [char \*, int] |
| 657 | Like ``s#``, but accepts any object which implements the read-write buffer |
| 658 | interface. The :ctype:`char \*` variable is set to point to the first byte of |
| 659 | the buffer, and the :ctype:`int` is set to the length of the buffer. Only |
| 660 | single-segment buffer objects are accepted; :exc:`TypeError` is raised for all |
| 661 | others. |
| 662 | |
| 663 | ``(items)`` (tuple) [*matching-items*] |
| 664 | The object must be a Python sequence whose length is the number of format units |
| 665 | in *items*. The C arguments must correspond to the individual format units in |
| 666 | *items*. Format units for sequences may be nested. |
| 667 | |
| 668 | .. note:: |
| 669 | |
| 670 | Prior to Python version 1.5.2, this format specifier only accepted a tuple |
| 671 | containing the individual parameters, not an arbitrary sequence. Code which |
| 672 | previously caused :exc:`TypeError` to be raised here may now proceed without an |
| 673 | exception. This is not expected to be a problem for existing code. |
| 674 | |
| 675 | It is possible to pass Python long integers where integers are requested; |
| 676 | however no proper range checking is done --- the most significant bits are |
| 677 | silently truncated when the receiving field is too small to receive the value |
| 678 | (actually, the semantics are inherited from downcasts in C --- your mileage may |
| 679 | vary). |
| 680 | |
| 681 | A few other characters have a meaning in a format string. These may not occur |
| 682 | inside nested parentheses. They are: |
| 683 | |
| 684 | ``|`` |
| 685 | Indicates that the remaining arguments in the Python argument list are optional. |
| 686 | The C variables corresponding to optional arguments should be initialized to |
| 687 | their default value --- when an optional argument is not specified, |
| 688 | :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C |
| 689 | variable(s). |
| 690 | |
| 691 | ``:`` |
| 692 | The list of format units ends here; the string after the colon is used as the |
| 693 | function name in error messages (the "associated value" of the exception that |
| 694 | :cfunc:`PyArg_ParseTuple` raises). |
| 695 | |
| 696 | ``;`` |
| 697 | The list of format units ends here; the string after the semicolon is used as |
| 698 | the error message *instead* of the default error message. Clearly, ``:`` and |
| 699 | ``;`` mutually exclude each other. |
| 700 | |
| 701 | Note that any Python object references which are provided to the caller are |
| 702 | *borrowed* references; do not decrement their reference count! |
| 703 | |
| 704 | Additional arguments passed to these functions must be addresses of variables |
| 705 | whose type is determined by the format string; these are used to store values |
| 706 | from the input tuple. There are a few cases, as described in the list of format |
| 707 | units above, where these parameters are used as input values; they should match |
| 708 | what is specified for the corresponding format unit in that case. |
| 709 | |
| 710 | For the conversion to succeed, the *arg* object must match the format and the |
| 711 | format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions |
| 712 | return true, otherwise they return false and raise an appropriate exception. |
| 713 | |
| 714 | |
| 715 | .. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) |
| 716 | |
| 717 | Parse the parameters of a function that takes only positional parameters into |
| 718 | local variables. Returns true on success; on failure, it returns false and |
| 719 | raises the appropriate exception. |
| 720 | |
| 721 | |
| 722 | .. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs) |
| 723 | |
| 724 | Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather |
| 725 | than a variable number of arguments. |
| 726 | |
| 727 | |
| 728 | .. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...) |
| 729 | |
| 730 | Parse the parameters of a function that takes both positional and keyword |
| 731 | parameters into local variables. Returns true on success; on failure, it |
| 732 | returns false and raises the appropriate exception. |
| 733 | |
| 734 | |
| 735 | .. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs) |
| 736 | |
| 737 | Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a |
| 738 | va_list rather than a variable number of arguments. |
| 739 | |
| 740 | |
| 741 | .. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...) |
| 742 | |
| 743 | Function used to deconstruct the argument lists of "old-style" functions --- |
| 744 | these are functions which use the :const:`METH_OLDARGS` parameter parsing |
| 745 | method. This is not recommended for use in parameter parsing in new code, and |
| 746 | most code in the standard interpreter has been modified to no longer use this |
| 747 | for that purpose. It does remain a convenient way to decompose other tuples, |
| 748 | however, and may continue to be used for that purpose. |
| 749 | |
| 750 | |
| 751 | .. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) |
| 752 | |
| 753 | A simpler form of parameter retrieval which does not use a format string to |
| 754 | specify the types of the arguments. Functions which use this method to retrieve |
| 755 | their parameters should be declared as :const:`METH_VARARGS` in function or |
| 756 | method tables. The tuple containing the actual parameters should be passed as |
| 757 | *args*; it must actually be a tuple. The length of the tuple must be at least |
| 758 | *min* and no more than *max*; *min* and *max* may be equal. Additional |
| 759 | arguments must be passed to the function, each of which should be a pointer to a |
| 760 | :ctype:`PyObject\*` variable; these will be filled in with the values from |
| 761 | *args*; they will contain borrowed references. The variables which correspond |
| 762 | to optional parameters not given by *args* will not be filled in; these should |
| 763 | be initialized by the caller. This function returns true on success and false if |
| 764 | *args* is not a tuple or contains the wrong number of elements; an exception |
| 765 | will be set if there was a failure. |
| 766 | |
| 767 | This is an example of the use of this function, taken from the sources for the |
| 768 | :mod:`_weakref` helper module for weak references:: |
| 769 | |
| 770 | static PyObject * |
| 771 | weakref_ref(PyObject *self, PyObject *args) |
| 772 | { |
| 773 | PyObject *object; |
| 774 | PyObject *callback = NULL; |
| 775 | PyObject *result = NULL; |
| 776 | |
| 777 | if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) { |
| 778 | result = PyWeakref_NewRef(object, callback); |
| 779 | } |
| 780 | return result; |
| 781 | } |
| 782 | |
| 783 | The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to |
| 784 | this call to :cfunc:`PyArg_ParseTuple`:: |
| 785 | |
| 786 | PyArg_ParseTuple(args, "O|O:ref", &object, &callback) |
| 787 | |
| 788 | .. versionadded:: 2.2 |
| 789 | |
| 790 | |
| 791 | .. cfunction:: PyObject* Py_BuildValue(const char *format, ...) |
| 792 | |
| 793 | Create a new value based on a format string similar to those accepted by the |
| 794 | :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. Returns |
| 795 | the value or *NULL* in the case of an error; an exception will be raised if |
| 796 | *NULL* is returned. |
| 797 | |
| 798 | :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple only if |
| 799 | its format string contains two or more format units. If the format string is |
| 800 | empty, it returns ``None``; if it contains exactly one format unit, it returns |
| 801 | whatever object is described by that format unit. To force it to return a tuple |
| 802 | of size 0 or one, parenthesize the format string. |
| 803 | |
| 804 | When memory buffers are passed as parameters to supply data to build objects, as |
| 805 | for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided |
| 806 | by the caller are never referenced by the objects created by |
| 807 | :cfunc:`Py_BuildValue`. In other words, if your code invokes :cfunc:`malloc` |
| 808 | and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is |
| 809 | responsible for calling :cfunc:`free` for that memory once |
| 810 | :cfunc:`Py_BuildValue` returns. |
| 811 | |
| 812 | In the following description, the quoted form is the format unit; the entry in |
| 813 | (round) parentheses is the Python object type that the format unit will return; |
| 814 | and the entry in [square] brackets is the type of the C value(s) to be passed. |
| 815 | |
| 816 | The characters space, tab, colon and comma are ignored in format strings (but |
| 817 | not within format units such as ``s#``). This can be used to make long format |
| 818 | strings a tad more readable. |
| 819 | |
| 820 | ``s`` (string) [char \*] |
| 821 | Convert a null-terminated C string to a Python object. If the C string pointer |
| 822 | is *NULL*, ``None`` is used. |
| 823 | |
| 824 | ``s#`` (string) [char \*, int] |
| 825 | Convert a C string and its length to a Python object. If the C string pointer |
| 826 | is *NULL*, the length is ignored and ``None`` is returned. |
| 827 | |
| 828 | ``z`` (string or ``None``) [char \*] |
| 829 | Same as ``s``. |
| 830 | |
| 831 | ``z#`` (string or ``None``) [char \*, int] |
| 832 | Same as ``s#``. |
| 833 | |
| 834 | ``u`` (Unicode string) [Py_UNICODE \*] |
| 835 | Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python |
| 836 | Unicode object. If the Unicode buffer pointer is *NULL*, ``None`` is returned. |
| 837 | |
| 838 | ``u#`` (Unicode string) [Py_UNICODE \*, int] |
| 839 | Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python |
| 840 | Unicode object. If the Unicode buffer pointer is *NULL*, the length is ignored |
| 841 | and ``None`` is returned. |
| 842 | |
| 843 | ``i`` (integer) [int] |
| 844 | Convert a plain C :ctype:`int` to a Python integer object. |
| 845 | |
| 846 | ``b`` (integer) [char] |
| 847 | Convert a plain C :ctype:`char` to a Python integer object. |
| 848 | |
| 849 | ``h`` (integer) [short int] |
| 850 | Convert a plain C :ctype:`short int` to a Python integer object. |
| 851 | |
| 852 | ``l`` (integer) [long int] |
| 853 | Convert a C :ctype:`long int` to a Python integer object. |
| 854 | |
| 855 | ``B`` (integer) [unsigned char] |
| 856 | Convert a C :ctype:`unsigned char` to a Python integer object. |
| 857 | |
| 858 | ``H`` (integer) [unsigned short int] |
| 859 | Convert a C :ctype:`unsigned short int` to a Python integer object. |
| 860 | |
| 861 | ``I`` (integer/long) [unsigned int] |
| 862 | Convert a C :ctype:`unsigned int` to a Python integer object or a Python long |
| 863 | integer object, if it is larger than ``sys.maxint``. |
| 864 | |
| 865 | ``k`` (integer/long) [unsigned long] |
| 866 | Convert a C :ctype:`unsigned long` to a Python integer object or a Python long |
| 867 | integer object, if it is larger than ``sys.maxint``. |
| 868 | |
| 869 | ``L`` (long) [PY_LONG_LONG] |
| 870 | Convert a C :ctype:`long long` to a Python long integer object. Only available |
| 871 | on platforms that support :ctype:`long long`. |
| 872 | |
| 873 | ``K`` (long) [unsigned PY_LONG_LONG] |
| 874 | Convert a C :ctype:`unsigned long long` to a Python long integer object. Only |
| 875 | available on platforms that support :ctype:`unsigned long long`. |
| 876 | |
| 877 | ``n`` (int) [Py_ssize_t] |
| 878 | Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer. |
| 879 | |
| 880 | .. versionadded:: 2.5 |
| 881 | |
| 882 | ``c`` (string of length 1) [char] |
| 883 | Convert a C :ctype:`int` representing a character to a Python string of length |
| 884 | 1. |
| 885 | |
| 886 | ``d`` (float) [double] |
| 887 | Convert a C :ctype:`double` to a Python floating point number. |
| 888 | |
| 889 | ``f`` (float) [float] |
| 890 | Same as ``d``. |
| 891 | |
| 892 | ``D`` (complex) [Py_complex \*] |
| 893 | Convert a C :ctype:`Py_complex` structure to a Python complex number. |
| 894 | |
| 895 | ``O`` (object) [PyObject \*] |
| 896 | Pass a Python object untouched (except for its reference count, which is |
| 897 | incremented by one). If the object passed in is a *NULL* pointer, it is assumed |
| 898 | that this was caused because the call producing the argument found an error and |
| 899 | set an exception. Therefore, :cfunc:`Py_BuildValue` will return *NULL* but won't |
| 900 | raise an exception. If no exception has been raised yet, :exc:`SystemError` is |
| 901 | set. |
| 902 | |
| 903 | ``S`` (object) [PyObject \*] |
| 904 | Same as ``O``. |
| 905 | |
| 906 | ``N`` (object) [PyObject \*] |
| 907 | Same as ``O``, except it doesn't increment the reference count on the object. |
| 908 | Useful when the object is created by a call to an object constructor in the |
| 909 | argument list. |
| 910 | |
| 911 | ``O&`` (object) [*converter*, *anything*] |
| 912 | Convert *anything* to a Python object through a *converter* function. The |
| 913 | function is called with *anything* (which should be compatible with :ctype:`void |
| 914 | \*`) as its argument and should return a "new" Python object, or *NULL* if an |
| 915 | error occurred. |
| 916 | |
| 917 | ``(items)`` (tuple) [*matching-items*] |
| 918 | Convert a sequence of C values to a Python tuple with the same number of items. |
| 919 | |
| 920 | ``[items]`` (list) [*matching-items*] |
| 921 | Convert a sequence of C values to a Python list with the same number of items. |
| 922 | |
| 923 | ``{items}`` (dictionary) [*matching-items*] |
| 924 | Convert a sequence of C values to a Python dictionary. Each pair of consecutive |
| 925 | C values adds one item to the dictionary, serving as key and value, |
| 926 | respectively. |
| 927 | |
| 928 | If there is an error in the format string, the :exc:`SystemError` exception is |
| 929 | set and *NULL* returned. |
| 930 | |
| 931 | |
| 932 | .. _string-conversion: |
| 933 | |
| 934 | String conversion and formatting |
| 935 | ================================ |
| 936 | |
| 937 | Functions for number conversion and formatted string output. |
| 938 | |
| 939 | |
| 940 | .. cfunction:: int PyOS_snprintf(char *str, size_t size, const char *format, ...) |
| 941 | |
| 942 | Output not more than *size* bytes to *str* according to the format string |
| 943 | *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`. |
| 944 | |
| 945 | |
| 946 | .. cfunction:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) |
| 947 | |
| 948 | Output not more than *size* bytes to *str* according to the format string |
| 949 | *format* and the variable argument list *va*. Unix man page |
| 950 | :manpage:`vsnprintf(2)`. |
| 951 | |
| 952 | :cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library |
| 953 | functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to |
| 954 | guarantee consistent behavior in corner cases, which the Standard C functions do |
| 955 | not. |
| 956 | |
| 957 | The wrappers ensure that *str*[*size*-1] is always ``'\0'`` upon return. They |
| 958 | never write more than *size* bytes (including the trailing ``'\0'`` into str. |
| 959 | Both functions require that ``str != NULL``, ``size > 0`` and ``format != |
| 960 | NULL``. |
| 961 | |
| 962 | If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to |
| 963 | avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a |
| 964 | *Py_FatalError*. |
| 965 | |
| 966 | The return value (*rv*) for these functions should be interpreted as follows: |
| 967 | |
| 968 | * When ``0 <= rv < size``, the output conversion was successful and *rv* |
| 969 | characters were written to *str* (excluding the trailing ``'\0'`` byte at |
| 970 | *str*[*rv*]). |
| 971 | |
| 972 | * When ``rv >= size``, the output conversion was truncated and a buffer with |
| 973 | ``rv + 1`` bytes would have been needed to succeed. *str*[*size*-1] is ``'\0'`` |
| 974 | in this case. |
| 975 | |
| 976 | * When ``rv < 0``, "something bad happened." *str*[*size*-1] is ``'\0'`` in |
| 977 | this case too, but the rest of *str* is undefined. The exact cause of the error |
| 978 | depends on the underlying platform. |
| 979 | |
| 980 | The following functions provide locale-independent string to number conversions. |
| 981 | |
| 982 | |
| 983 | .. cfunction:: double PyOS_ascii_strtod(const char *nptr, char **endptr) |
| 984 | |
| 985 | Convert a string to a :ctype:`double`. This function behaves like the Standard C |
| 986 | function :cfunc:`strtod` does in the C locale. It does this without changing the |
| 987 | current locale, since that would not be thread-safe. |
| 988 | |
| 989 | :cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration |
| 990 | files or other non-user input that should be locale independent. |
| 991 | |
| 992 | .. versionadded:: 2.4 |
| 993 | |
| 994 | See the Unix man page :manpage:`strtod(2)` for details. |
| 995 | |
| 996 | |
| 997 | .. cfunction:: char * PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d) |
| 998 | |
| 999 | Convert a :ctype:`double` to a string using the ``'.'`` as the decimal |
| 1000 | separator. *format* is a :cfunc:`printf`\ -style format string specifying the |
| 1001 | number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``, |
| 1002 | ``'F'``, ``'g'`` and ``'G'``. |
| 1003 | |
| 1004 | The return value is a pointer to *buffer* with the converted string or NULL if |
| 1005 | the conversion failed. |
| 1006 | |
| 1007 | .. versionadded:: 2.4 |
| 1008 | |
| 1009 | |
| 1010 | .. cfunction:: double PyOS_ascii_atof(const char *nptr) |
| 1011 | |
| 1012 | Convert a string to a :ctype:`double` in a locale-independent way. |
| 1013 | |
| 1014 | .. versionadded:: 2.4 |
| 1015 | |
| 1016 | See the Unix man page :manpage:`atof(2)` for details. |
| 1017 | |
Georg Brandl | 16f1df9 | 2007-12-01 22:24:47 +0000 | [diff] [blame^] | 1018 | |
| 1019 | .. _reflection: |
| 1020 | |
| 1021 | Reflection |
| 1022 | ========== |
| 1023 | |
| 1024 | .. cfunction:: PyObject* PyEval_GetBuiltins() |
| 1025 | |
| 1026 | Return a dictionary of the builtins in the current execution frame, |
| 1027 | or the interpreter of the thread state if no frame is currently executing. |
| 1028 | |
| 1029 | |
| 1030 | .. cfunction:: PyObject* PyEval_GetLocals() |
| 1031 | |
| 1032 | Return a dictionary of the local variables in the current execution frame, |
| 1033 | or *NULL* if no frame is currently executing. |
| 1034 | |
| 1035 | |
| 1036 | .. cfunction:: PyObject* PyEval_GetGlobals() |
| 1037 | |
| 1038 | Return a dictionary of the global variables in the current execution frame, |
| 1039 | or *NULL* if no frame is currently executing. |
| 1040 | |
| 1041 | |
| 1042 | .. cfunction:: PyFrameObject* PyEval_GetFrame() |
| 1043 | |
| 1044 | Return the current thread state's frame, which is *NULL* if no frame is |
| 1045 | currently executing. |
| 1046 | |
| 1047 | |
| 1048 | .. cfunction:: int PyEval_GetRestricted() |
| 1049 | |
| 1050 | If there is a current frame and it is executing in restricted mode, return true, |
| 1051 | otherwise false. |
| 1052 | |
| 1053 | |
| 1054 | .. cfunction:: const char* PyEval_GetFuncName(PyObject *func) |
| 1055 | |
| 1056 | Return the name of *func* if it is a function, class or instance object, else the |
| 1057 | name of *func*\s type. |
| 1058 | |
| 1059 | |
| 1060 | .. cfunction:: const char* PyEval_GetFuncDesc(PyObject *func) |
| 1061 | |
| 1062 | Return a description string, depending on the type of *func*. |
| 1063 | Return values include "()" for functions and methods, " constructor", |
| 1064 | " instance", and " object". Concatenated with the result of |
| 1065 | :cfunc:`PyEval_GetFuncName`, the result will be a description of |
| 1066 | *func*. |