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