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