blob: 71e9560017145255f3077d056f37d7faf3ee2217 [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
Guido van Rossumfb67be22007-08-29 18:38:11 +0000487``Z`` (Unicode or ``None``) [Py_UNICODE \*]
488 Like ``s``, but the Python object may also be ``None``, in which case the C
489 pointer is set to *NULL*.
490
491``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int]
492 This is to ``u#`` as ``Z`` is to ``u``.
493
Georg Brandl116aa622007-08-15 14:28:22 +0000494``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
495 This variant on ``s`` is used for encoding Unicode and objects convertible to
496 Unicode into a character buffer. It only works for encoded data without embedded
497 NUL bytes.
498
499 This format requires two arguments. The first is only used as input, and
500 must be a :ctype:`const char\*` which points to the name of an encoding as a
501 NUL-terminated string, or *NULL*, in which case the default encoding is used.
502 An exception is raised if the named encoding is not known to Python. The
503 second argument must be a :ctype:`char\*\*`; the value of the pointer it
504 references will be set to a buffer with the contents of the argument text.
505 The text will be encoded in the encoding specified by the first argument.
506
507 :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the
508 encoded data into this buffer and adjust *\*buffer* to reference the newly
509 allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to
510 free the allocated buffer after use.
511
512``et`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
513 Same as ``es`` except that 8-bit string objects are passed through without
514 recoding them. Instead, the implementation assumes that the string object uses
515 the encoding passed in as parameter.
516
517``es#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
518 This variant on ``s#`` is used for encoding Unicode and objects convertible to
519 Unicode into a character buffer. Unlike the ``es`` format, this variant allows
520 input data which contains NUL characters.
521
522 It requires three arguments. The first is only used as input, and must be a
523 :ctype:`const char\*` which points to the name of an encoding as a
524 NUL-terminated string, or *NULL*, in which case the default encoding is used.
525 An exception is raised if the named encoding is not known to Python. The
526 second argument must be a :ctype:`char\*\*`; the value of the pointer it
527 references will be set to a buffer with the contents of the argument text.
528 The text will be encoded in the encoding specified by the first argument.
529 The third argument must be a pointer to an integer; the referenced integer
530 will be set to the number of bytes in the output buffer.
531
532 There are two modes of operation:
533
534 If *\*buffer* points a *NULL* pointer, the function will allocate a buffer of
535 the needed size, copy the encoded data into this buffer and set *\*buffer* to
536 reference the newly allocated storage. The caller is responsible for calling
537 :cfunc:`PyMem_Free` to free the allocated buffer after usage.
538
539 If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer),
540 :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the
541 initial value of *\*buffer_length* as the buffer size. It will then copy the
542 encoded data into the buffer and NUL-terminate it. If the buffer is not large
543 enough, a :exc:`ValueError` will be set.
544
545 In both cases, *\*buffer_length* is set to the length of the encoded data
546 without the trailing NUL byte.
547
548``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
549 Same as ``es#`` except that string objects are passed through without recoding
550 them. Instead, the implementation assumes that the string object uses the
551 encoding passed in as parameter.
552
553``b`` (integer) [char]
554 Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
555
556``B`` (integer) [unsigned char]
557 Convert a Python integer to a tiny int without overflow checking, stored in a C
558 :ctype:`unsigned char`.
559
560 .. versionadded:: 2.3
561
562``h`` (integer) [short int]
563 Convert a Python integer to a C :ctype:`short int`.
564
565``H`` (integer) [unsigned short int]
566 Convert a Python integer to a C :ctype:`unsigned short int`, without overflow
567 checking.
568
569 .. versionadded:: 2.3
570
571``i`` (integer) [int]
572 Convert a Python integer to a plain C :ctype:`int`.
573
574``I`` (integer) [unsigned int]
575 Convert a Python integer to a C :ctype:`unsigned int`, without overflow
576 checking.
577
578 .. versionadded:: 2.3
579
580``l`` (integer) [long int]
581 Convert a Python integer to a C :ctype:`long int`.
582
583``k`` (integer) [unsigned long]
584 Convert a Python integer or long integer to a C :ctype:`unsigned long` without
585 overflow checking.
586
587 .. versionadded:: 2.3
588
589``L`` (integer) [PY_LONG_LONG]
590 Convert a Python integer to a C :ctype:`long long`. This format is only
591 available on platforms that support :ctype:`long long` (or :ctype:`_int64` on
592 Windows).
593
594``K`` (integer) [unsigned PY_LONG_LONG]
595 Convert a Python integer or long integer to a C :ctype:`unsigned long long`
596 without overflow checking. This format is only available on platforms that
597 support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows).
598
599 .. versionadded:: 2.3
600
601``n`` (integer) [Py_ssize_t]
602 Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`.
603
604 .. versionadded:: 2.5
605
606``c`` (string of length 1) [char]
607 Convert a Python character, represented as a string of length 1, to a C
608 :ctype:`char`.
609
610``f`` (float) [float]
611 Convert a Python floating point number to a C :ctype:`float`.
612
613``d`` (float) [double]
614 Convert a Python floating point number to a C :ctype:`double`.
615
616``D`` (complex) [Py_complex]
617 Convert a Python complex number to a C :ctype:`Py_complex` structure.
618
619``O`` (object) [PyObject \*]
620 Store a Python object (without any conversion) in a C object pointer. The C
621 program thus receives the actual object that was passed. The object's reference
622 count is not increased. The pointer stored is not *NULL*.
623
624``O!`` (object) [*typeobject*, PyObject \*]
625 Store a Python object in a C object pointer. This is similar to ``O``, but
626 takes two C arguments: the first is the address of a Python type object, the
627 second is the address of the C variable (of type :ctype:`PyObject\*`) into which
628 the object pointer is stored. If the Python object does not have the required
629 type, :exc:`TypeError` is raised.
630
631``O&`` (object) [*converter*, *anything*]
632 Convert a Python object to a C variable through a *converter* function. This
633 takes two arguments: the first is a function, the second is the address of a C
634 variable (of arbitrary type), converted to :ctype:`void \*`. The *converter*
635 function in turn is called as follows::
636
637 status = converter(object, address);
638
639 where *object* is the Python object to be converted and *address* is the
640 :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function.
641 The returned *status* should be ``1`` for a successful conversion and ``0`` if
642 the conversion has failed. When the conversion fails, the *converter* function
643 should raise an exception.
644
645``S`` (string) [PyStringObject \*]
646 Like ``O`` but requires that the Python object is a string object. Raises
647 :exc:`TypeError` if the object is not a string object. The C variable may also
648 be declared as :ctype:`PyObject\*`.
649
650``U`` (Unicode string) [PyUnicodeObject \*]
651 Like ``O`` but requires that the Python object is a Unicode object. Raises
652 :exc:`TypeError` if the object is not a Unicode object. The C variable may also
653 be declared as :ctype:`PyObject\*`.
654
655``t#`` (read-only character buffer) [char \*, int]
656 Like ``s#``, but accepts any object which implements the read-only buffer
657 interface. The :ctype:`char\*` variable is set to point to the first byte of
658 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
659 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
660 others.
661
662``w`` (read-write character buffer) [char \*]
663 Similar to ``s``, but accepts any object which implements the read-write buffer
664 interface. The caller must determine the length of the buffer by other means,
665 or use ``w#`` instead. Only single-segment buffer objects are accepted;
666 :exc:`TypeError` is raised for all others.
667
668``w#`` (read-write character buffer) [char \*, int]
669 Like ``s#``, but accepts any object which implements the read-write buffer
670 interface. The :ctype:`char \*` variable is set to point to the first byte of
671 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
672 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
673 others.
674
675``(items)`` (tuple) [*matching-items*]
676 The object must be a Python sequence whose length is the number of format units
677 in *items*. The C arguments must correspond to the individual format units in
678 *items*. Format units for sequences may be nested.
679
680 .. note::
681
682 Prior to Python version 1.5.2, this format specifier only accepted a tuple
683 containing the individual parameters, not an arbitrary sequence. Code which
684 previously caused :exc:`TypeError` to be raised here may now proceed without an
685 exception. This is not expected to be a problem for existing code.
686
687It is possible to pass Python long integers where integers are requested;
688however no proper range checking is done --- the most significant bits are
689silently truncated when the receiving field is too small to receive the value
690(actually, the semantics are inherited from downcasts in C --- your mileage may
691vary).
692
693A few other characters have a meaning in a format string. These may not occur
694inside nested parentheses. They are:
695
696``|``
697 Indicates that the remaining arguments in the Python argument list are optional.
698 The C variables corresponding to optional arguments should be initialized to
699 their default value --- when an optional argument is not specified,
700 :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C
701 variable(s).
702
703``:``
704 The list of format units ends here; the string after the colon is used as the
705 function name in error messages (the "associated value" of the exception that
706 :cfunc:`PyArg_ParseTuple` raises).
707
708``;``
709 The list of format units ends here; the string after the semicolon is used as
710 the error message *instead* of the default error message. Clearly, ``:`` and
711 ``;`` mutually exclude each other.
712
713Note that any Python object references which are provided to the caller are
714*borrowed* references; do not decrement their reference count!
715
716Additional arguments passed to these functions must be addresses of variables
717whose type is determined by the format string; these are used to store values
718from the input tuple. There are a few cases, as described in the list of format
719units above, where these parameters are used as input values; they should match
720what is specified for the corresponding format unit in that case.
721
722For the conversion to succeed, the *arg* object must match the format and the
723format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions
724return true, otherwise they return false and raise an appropriate exception.
725
726
727.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
728
729 Parse the parameters of a function that takes only positional parameters into
730 local variables. Returns true on success; on failure, it returns false and
731 raises the appropriate exception.
732
733
734.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
735
736 Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather
737 than a variable number of arguments.
738
739
740.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
741
742 Parse the parameters of a function that takes both positional and keyword
743 parameters into local variables. Returns true on success; on failure, it
744 returns false and raises the appropriate exception.
745
746
747.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
748
749 Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a
750 va_list rather than a variable number of arguments.
751
752
Georg Brandl85eb8c12007-08-31 16:33:38 +0000753.. XXX deprecated, will be removed
Georg Brandl116aa622007-08-15 14:28:22 +0000754.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...)
755
756 Function used to deconstruct the argument lists of "old-style" functions ---
757 these are functions which use the :const:`METH_OLDARGS` parameter parsing
758 method. This is not recommended for use in parameter parsing in new code, and
759 most code in the standard interpreter has been modified to no longer use this
760 for that purpose. It does remain a convenient way to decompose other tuples,
761 however, and may continue to be used for that purpose.
762
763
764.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
765
766 A simpler form of parameter retrieval which does not use a format string to
767 specify the types of the arguments. Functions which use this method to retrieve
768 their parameters should be declared as :const:`METH_VARARGS` in function or
769 method tables. The tuple containing the actual parameters should be passed as
770 *args*; it must actually be a tuple. The length of the tuple must be at least
771 *min* and no more than *max*; *min* and *max* may be equal. Additional
772 arguments must be passed to the function, each of which should be a pointer to a
773 :ctype:`PyObject\*` variable; these will be filled in with the values from
774 *args*; they will contain borrowed references. The variables which correspond
775 to optional parameters not given by *args* will not be filled in; these should
776 be initialized by the caller. This function returns true on success and false if
777 *args* is not a tuple or contains the wrong number of elements; an exception
778 will be set if there was a failure.
779
780 This is an example of the use of this function, taken from the sources for the
781 :mod:`_weakref` helper module for weak references::
782
783 static PyObject *
784 weakref_ref(PyObject *self, PyObject *args)
785 {
786 PyObject *object;
787 PyObject *callback = NULL;
788 PyObject *result = NULL;
789
790 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
791 result = PyWeakref_NewRef(object, callback);
792 }
793 return result;
794 }
795
796 The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to
797 this call to :cfunc:`PyArg_ParseTuple`::
798
799 PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
800
801 .. versionadded:: 2.2
802
803
804.. cfunction:: PyObject* Py_BuildValue(const char *format, ...)
805
806 Create a new value based on a format string similar to those accepted by the
807 :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. Returns
808 the value or *NULL* in the case of an error; an exception will be raised if
809 *NULL* is returned.
810
811 :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple only if
812 its format string contains two or more format units. If the format string is
813 empty, it returns ``None``; if it contains exactly one format unit, it returns
814 whatever object is described by that format unit. To force it to return a tuple
815 of size 0 or one, parenthesize the format string.
816
817 When memory buffers are passed as parameters to supply data to build objects, as
818 for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided
819 by the caller are never referenced by the objects created by
820 :cfunc:`Py_BuildValue`. In other words, if your code invokes :cfunc:`malloc`
821 and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is
822 responsible for calling :cfunc:`free` for that memory once
823 :cfunc:`Py_BuildValue` returns.
824
825 In the following description, the quoted form is the format unit; the entry in
826 (round) parentheses is the Python object type that the format unit will return;
827 and the entry in [square] brackets is the type of the C value(s) to be passed.
828
829 The characters space, tab, colon and comma are ignored in format strings (but
830 not within format units such as ``s#``). This can be used to make long format
831 strings a tad more readable.
832
833 ``s`` (string) [char \*]
834 Convert a null-terminated C string to a Python object. If the C string pointer
835 is *NULL*, ``None`` is used.
836
837 ``s#`` (string) [char \*, int]
838 Convert a C string and its length to a Python object. If the C string pointer
839 is *NULL*, the length is ignored and ``None`` is returned.
840
841 ``z`` (string or ``None``) [char \*]
842 Same as ``s``.
843
844 ``z#`` (string or ``None``) [char \*, int]
845 Same as ``s#``.
846
847 ``u`` (Unicode string) [Py_UNICODE \*]
848 Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python
849 Unicode object. If the Unicode buffer pointer is *NULL*, ``None`` is returned.
850
851 ``u#`` (Unicode string) [Py_UNICODE \*, int]
852 Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python
853 Unicode object. If the Unicode buffer pointer is *NULL*, the length is ignored
854 and ``None`` is returned.
855
856 ``U`` (string) [char \*]
857 Convert a null-terminated C string to a Python unicode object. If the C string
858 pointer is *NULL*, ``None`` is used.
859
860 ``U#`` (string) [char \*, int]
861 Convert a C string and its length to a Python unicode object. If the C string
862 pointer is *NULL*, the length is ignored and ``None`` is returned.
863
864 ``i`` (integer) [int]
865 Convert a plain C :ctype:`int` to a Python integer object.
866
867 ``b`` (integer) [char]
868 Convert a plain C :ctype:`char` to a Python integer object.
869
870 ``h`` (integer) [short int]
871 Convert a plain C :ctype:`short int` to a Python integer object.
872
873 ``l`` (integer) [long int]
874 Convert a C :ctype:`long int` to a Python integer object.
875
876 ``B`` (integer) [unsigned char]
877 Convert a C :ctype:`unsigned char` to a Python integer object.
878
879 ``H`` (integer) [unsigned short int]
880 Convert a C :ctype:`unsigned short int` to a Python integer object.
881
882 ``I`` (integer/long) [unsigned int]
883 Convert a C :ctype:`unsigned int` to a Python integer object or a Python long
884 integer object, if it is larger than ``sys.maxint``.
885
886 ``k`` (integer/long) [unsigned long]
887 Convert a C :ctype:`unsigned long` to a Python integer object or a Python long
888 integer object, if it is larger than ``sys.maxint``.
889
890 ``L`` (long) [PY_LONG_LONG]
891 Convert a C :ctype:`long long` to a Python long integer object. Only available
892 on platforms that support :ctype:`long long`.
893
894 ``K`` (long) [unsigned PY_LONG_LONG]
895 Convert a C :ctype:`unsigned long long` to a Python long integer object. Only
896 available on platforms that support :ctype:`unsigned long long`.
897
898 ``n`` (int) [Py_ssize_t]
899 Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer.
900
901 .. versionadded:: 2.5
902
903 ``c`` (string of length 1) [char]
904 Convert a C :ctype:`int` representing a character to a Python string of length
905 1.
906
907 ``d`` (float) [double]
908 Convert a C :ctype:`double` to a Python floating point number.
909
910 ``f`` (float) [float]
911 Same as ``d``.
912
913 ``D`` (complex) [Py_complex \*]
914 Convert a C :ctype:`Py_complex` structure to a Python complex number.
915
916 ``O`` (object) [PyObject \*]
917 Pass a Python object untouched (except for its reference count, which is
918 incremented by one). If the object passed in is a *NULL* pointer, it is assumed
919 that this was caused because the call producing the argument found an error and
920 set an exception. Therefore, :cfunc:`Py_BuildValue` will return *NULL* but won't
921 raise an exception. If no exception has been raised yet, :exc:`SystemError` is
922 set.
923
924 ``S`` (object) [PyObject \*]
925 Same as ``O``.
926
927 ``N`` (object) [PyObject \*]
928 Same as ``O``, except it doesn't increment the reference count on the object.
929 Useful when the object is created by a call to an object constructor in the
930 argument list.
931
932 ``O&`` (object) [*converter*, *anything*]
933 Convert *anything* to a Python object through a *converter* function. The
934 function is called with *anything* (which should be compatible with :ctype:`void
935 \*`) as its argument and should return a "new" Python object, or *NULL* if an
936 error occurred.
937
938 ``(items)`` (tuple) [*matching-items*]
939 Convert a sequence of C values to a Python tuple with the same number of items.
940
941 ``[items]`` (list) [*matching-items*]
942 Convert a sequence of C values to a Python list with the same number of items.
943
944 ``{items}`` (dictionary) [*matching-items*]
945 Convert a sequence of C values to a Python dictionary. Each pair of consecutive
946 C values adds one item to the dictionary, serving as key and value,
947 respectively.
948
949 If there is an error in the format string, the :exc:`SystemError` exception is
950 set and *NULL* returned.
951
952
953.. _string-conversion:
954
955String conversion and formatting
956================================
957
958Functions for number conversion and formatted string output.
959
960
961.. cfunction:: int PyOS_snprintf(char *str, size_t size, const char *format, ...)
962
963 Output not more than *size* bytes to *str* according to the format string
964 *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`.
965
966
967.. cfunction:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
968
969 Output not more than *size* bytes to *str* according to the format string
970 *format* and the variable argument list *va*. Unix man page
971 :manpage:`vsnprintf(2)`.
972
973:cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library
974functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to
975guarantee consistent behavior in corner cases, which the Standard C functions do
976not.
977
978The wrappers ensure that *str*[*size*-1] is always ``'\0'`` upon return. They
979never write more than *size* bytes (including the trailing ``'\0'``) into str.
980Both functions require that ``str != NULL``, ``size > 0`` and ``format !=
981NULL``.
982
983If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to
984avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a
985*Py_FatalError*.
986
987The return value (*rv*) for these functions should be interpreted as follows:
988
989* When ``0 <= rv < size``, the output conversion was successful and *rv*
990 characters were written to *str* (excluding the trailing ``'\0'`` byte at
991 *str*[*rv*]).
992
993* When ``rv >= size``, the output conversion was truncated and a buffer with
994 ``rv + 1`` bytes would have been needed to succeed. *str*[*size*-1] is ``'\0'``
995 in this case.
996
997* When ``rv < 0``, "something bad happened." *str*[*size*-1] is ``'\0'`` in
998 this case too, but the rest of *str* is undefined. The exact cause of the error
999 depends on the underlying platform.
1000
1001The following functions provide locale-independent string to number conversions.
1002
1003
1004.. cfunction:: double PyOS_ascii_strtod(const char *nptr, char **endptr)
1005
1006 Convert a string to a :ctype:`double`. This function behaves like the Standard C
1007 function :cfunc:`strtod` does in the C locale. It does this without changing the
1008 current locale, since that would not be thread-safe.
1009
1010 :cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration
1011 files or other non-user input that should be locale independent.
1012
1013 .. versionadded:: 2.4
1014
1015 See the Unix man page :manpage:`strtod(2)` for details.
1016
1017
1018.. cfunction:: char * PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d)
1019
1020 Convert a :ctype:`double` to a string using the ``'.'`` as the decimal
1021 separator. *format* is a :cfunc:`printf`\ -style format string specifying the
1022 number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``,
1023 ``'F'``, ``'g'`` and ``'G'``.
1024
1025 The return value is a pointer to *buffer* with the converted string or NULL if
1026 the conversion failed.
1027
1028 .. versionadded:: 2.4
1029
1030
1031.. cfunction:: double PyOS_ascii_atof(const char *nptr)
1032
1033 Convert a string to a :ctype:`double` in a locale-independent way.
1034
1035 .. versionadded:: 2.4
1036
1037 See the Unix man page :manpage:`atof(2)` for details.
1038