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