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