blob: 961f20045938bbcc23fed91fdab00789a2f42232 [file] [log] [blame]
Fred Drake3adf79e2001-10-12 19:01:43 +00001\chapter{Utilities \label{utilities}}
2
3The functions in this chapter perform various utility tasks, ranging
4from helping C code be more portable across platforms, using Python
5modules from C, and parsing function arguments and constructing Python
6values from C values.
7
8
9\section{Operating System Utilities \label{os}}
10
Martin v. Löwis29fafd82006-03-01 05:16:03 +000011\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, const char *filename}
Fred Drake3adf79e2001-10-12 19:01:43 +000012 Return true (nonzero) if the standard I/O file \var{fp} with name
13 \var{filename} is deemed interactive. This is the case for files
14 for which \samp{isatty(fileno(\var{fp}))} is true. If the global
15 flag \cdata{Py_InteractiveFlag} is true, this function also returns
16 true if the \var{filename} pointer is \NULL{} or if the name is
17 equal to one of the strings \code{'<stdin>'} or \code{'???'}.
18\end{cfuncdesc}
19
20\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
21 Return the time of last modification of the file \var{filename}.
22 The result is encoded in the same way as the timestamp returned by
23 the standard C library function \cfunction{time()}.
24\end{cfuncdesc}
25
26\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
27 Function to update some internal state after a process fork; this
28 should be called in the new process if the Python interpreter will
29 continue to be used. If a new executable is loaded into the new
30 process, this function does not need to be called.
31\end{cfuncdesc}
32
33\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
34 Return true when the interpreter runs out of stack space. This is a
35 reliable check, but is only available when \constant{USE_STACKCHECK}
36 is defined (currently on Windows using the Microsoft Visual \Cpp{}
Georg Brandlff528372005-09-15 11:16:28 +000037 compiler). \constant{USE_STACKCHECK} will be
Fred Drake3adf79e2001-10-12 19:01:43 +000038 defined automatically; you should never change the definition in
39 your own code.
40\end{cfuncdesc}
41
42\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
43 Return the current signal handler for signal \var{i}. This is a
44 thin wrapper around either \cfunction{sigaction()} or
45 \cfunction{signal()}. Do not call those functions directly!
46 \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void
47 (*)(int)}.
48\end{cfuncdesc}
49
50\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
51 Set the signal handler for signal \var{i} to be \var{h}; return the
52 old signal handler. This is a thin wrapper around either
53 \cfunction{sigaction()} or \cfunction{signal()}. Do not call those
54 functions directly! \ctype{PyOS_sighandler_t} is a typedef alias
55 for \ctype{void (*)(int)}.
56\end{cfuncdesc}
57
58
59\section{Process Control \label{processControl}}
60
Tim Peters7c321a82002-07-09 02:57:01 +000061\begin{cfuncdesc}{void}{Py_FatalError}{const char *message}
Fred Drake3adf79e2001-10-12 19:01:43 +000062 Print a fatal error message and kill the process. No cleanup is
63 performed. This function should only be invoked when a condition is
64 detected that would make it dangerous to continue using the Python
65 interpreter; e.g., when the object administration appears to be
66 corrupted. On \UNIX, the standard C library function
67 \cfunction{abort()}\ttindex{abort()} is called which will attempt to
68 produce a \file{core} file.
69\end{cfuncdesc}
70
71\begin{cfuncdesc}{void}{Py_Exit}{int status}
72 Exit the current process. This calls
73 \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and then calls the
74 standard C library function
75 \code{exit(\var{status})}\ttindex{exit()}.
76\end{cfuncdesc}
77
78\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
79 Register a cleanup function to be called by
80 \cfunction{Py_Finalize()}\ttindex{Py_Finalize()}. The cleanup
81 function will be called with no arguments and should return no
82 value. At most 32 \index{cleanup functions}cleanup functions can be
83 registered. When the registration is successful,
84 \cfunction{Py_AtExit()} returns \code{0}; on failure, it returns
85 \code{-1}. The cleanup function registered last is called first.
86 Each cleanup function will be called at most once. Since Python's
Andrew M. Kuchlingf54ac7e2004-08-10 19:01:50 +000087 internal finalization will have completed before the cleanup
Fred Drake3adf79e2001-10-12 19:01:43 +000088 function, no Python APIs should be called by \var{func}.
89\end{cfuncdesc}
90
91
92\section{Importing Modules \label{importing}}
93
Martin v. Löwis29fafd82006-03-01 05:16:03 +000094\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{const char *name}
Fred Drake3adf79e2001-10-12 19:01:43 +000095 This is a simplified interface to
96 \cfunction{PyImport_ImportModuleEx()} below, leaving the
97 \var{globals} and \var{locals} arguments set to \NULL. When the
98 \var{name} argument contains a dot (when it specifies a submodule of
99 a package), the \var{fromlist} argument is set to the list
100 \code{['*']} so that the return value is the named module rather
101 than the top-level package containing it as would otherwise be the
102 case. (Unfortunately, this has an additional side effect when
103 \var{name} in fact specifies a subpackage instead of a submodule:
104 the submodules specified in the package's \code{__all__} variable
105 are \index{package variable!\code{__all__}}
106 \withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return
107 a new reference to the imported module, or \NULL{} with an exception
Tim Peterscfd575d2004-08-02 03:46:45 +0000108 set on failure. Before Python 2.4, the module may still be created in
109 the failure case --- examine \code{sys.modules} to find out. Starting
110 with Python 2.4, a failing import of a module no longer leaves the
111 module in \code{sys.modules}.
112 \versionchanged[failing imports remove incomplete module objects]{2.4}
Fred Drake3adf79e2001-10-12 19:01:43 +0000113 \withsubitem{(in module sys)}{\ttindex{modules}}
114\end{cfuncdesc}
115
116\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name,
117 PyObject *globals, PyObject *locals, PyObject *fromlist}
118 Import a module. This is best described by referring to the
119 built-in Python function
120 \function{__import__()}\bifuncindex{__import__}, as the standard
121 \function{__import__()} function calls this function directly.
122
123 The return value is a new reference to the imported module or
Tim Peterscfd575d2004-08-02 03:46:45 +0000124 top-level package, or \NULL{} with an exception set on failure (before
125 Python 2.4, the
Fred Drake3adf79e2001-10-12 19:01:43 +0000126 module may still be created in this case). Like for
127 \function{__import__()}, the return value when a submodule of a
128 package was requested is normally the top-level package, unless a
129 non-empty \var{fromlist} was given.
Tim Peterscfd575d2004-08-02 03:46:45 +0000130 \versionchanged[failing imports remove incomplete module objects]{2.4}
Fred Drake3adf79e2001-10-12 19:01:43 +0000131\end{cfuncdesc}
132
133\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
134 This is a higher-level interface that calls the current ``import
135 hook function''. It invokes the \function{__import__()} function
136 from the \code{__builtins__} of the current globals. This means
137 that the import is done using whatever import hooks are installed in
138 the current environment, e.g. by \module{rexec}\refstmodindex{rexec}
139 or \module{ihooks}\refstmodindex{ihooks}.
140\end{cfuncdesc}
141
142\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossume7ba4952007-06-06 23:52:48 +0000143 Reload a module. Return a new reference to the reloaded module, or \NULL{}
Fred Drake3adf79e2001-10-12 19:01:43 +0000144 with an exception set on failure (the module still exists in this
145 case).
146\end{cfuncdesc}
147
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000148\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{const char *name}
Fred Drake3adf79e2001-10-12 19:01:43 +0000149 Return the module object corresponding to a module name. The
Brett Cannon711e7d92004-07-10 22:20:32 +0000150 \var{name} argument may be of the form \code{package.module}.
Fred Drake3adf79e2001-10-12 19:01:43 +0000151 First check the modules dictionary if there's one there, and if not,
Raymond Hettinger92016dc2003-09-22 15:27:11 +0000152 create a new one and insert it in the modules dictionary.
Fred Drake674dae22002-11-13 15:13:38 +0000153 Return \NULL{} with an exception set on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +0000154 \note{This function does not load or import the module; if the
155 module wasn't already loaded, you will get an empty module object.
156 Use \cfunction{PyImport_ImportModule()} or one of its variants to
Fred Drake674dae22002-11-13 15:13:38 +0000157 import a module. Package structures implied by a dotted name for
158 \var{name} are not created if not already present.}
Fred Drake3adf79e2001-10-12 19:01:43 +0000159\end{cfuncdesc}
160
161\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
162 Given a module name (possibly of the form \code{package.module}) and
163 a code object read from a Python bytecode file or obtained from the
164 built-in function \function{compile()}\bifuncindex{compile}, load
165 the module. Return a new reference to the module object, or \NULL{}
Tim Peterscfd575d2004-08-02 03:46:45 +0000166 with an exception set if an error occurred. Before Python 2.4, the module
167 could still be created in error cases. Starting with Python 2.4,
168 \var{name} is removed from \code{sys.modules} in error cases, and even
169 if \var{name} was already in \code{sys.modules} on entry to
170 \cfunction{PyImport_ExecCodeModule()}. Leaving incompletely initialized
171 modules in \code{sys.modules} is dangerous, as imports of such modules
172 have no way to know that the module object is an unknown (and probably
173 damaged with respect to the module author's intents) state.
174
175 This function will reload the module if it was already imported. See
Tim Petersfd7dc512004-08-02 04:30:37 +0000176 \cfunction{PyImport_ReloadModule()} for the intended way to reload a
Tim Peters0c6199e2004-08-02 04:14:10 +0000177 module.
Tim Peterscfd575d2004-08-02 03:46:45 +0000178
179 If \var{name} points to a dotted name of the
Fred Drake674dae22002-11-13 15:13:38 +0000180 form \code{package.module}, any package structures not already
181 created will still not be created.
Tim Peterscfd575d2004-08-02 03:46:45 +0000182
183 \versionchanged[\var{name} is removed from \code{sys.modules} in error cases]{2.4}
184
Fred Drake3adf79e2001-10-12 19:01:43 +0000185\end{cfuncdesc}
186
187\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
188 Return the magic number for Python bytecode files
189 (a.k.a. \file{.pyc} and \file{.pyo} files). The magic number should
190 be present in the first four bytes of the bytecode file, in
191 little-endian byte order.
192\end{cfuncdesc}
193
194\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
195 Return the dictionary used for the module administration
196 (a.k.a.\ \code{sys.modules}). Note that this is a per-interpreter
197 variable.
198\end{cfuncdesc}
199
200\begin{cfuncdesc}{void}{_PyImport_Init}{}
201 Initialize the import mechanism. For internal use only.
202\end{cfuncdesc}
203
204\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
205 Empty the module table. For internal use only.
206\end{cfuncdesc}
207
208\begin{cfuncdesc}{void}{_PyImport_Fini}{}
209 Finalize the import mechanism. For internal use only.
210\end{cfuncdesc}
211
212\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
213 For internal use only.
214\end{cfuncdesc}
215
216\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
217 For internal use only.
218\end{cfuncdesc}
219
220\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
221 Load a frozen module named \var{name}. Return \code{1} for success,
222 \code{0} if the module is not found, and \code{-1} with an exception
223 set if the initialization failed. To access the imported module on
224 a successful load, use \cfunction{PyImport_ImportModule()}. (Note
225 the misnomer --- this function would reload the module if it was
226 already imported.)
227\end{cfuncdesc}
228
229\begin{ctypedesc}[_frozen]{struct _frozen}
230 This is the structure type definition for frozen module descriptors,
231 as generated by the \program{freeze}\index{freeze utility} utility
232 (see \file{Tools/freeze/} in the Python source distribution). Its
233 definition, found in \file{Include/import.h}, is:
234
235\begin{verbatim}
236struct _frozen {
237 char *name;
238 unsigned char *code;
239 int size;
240};
241\end{verbatim}
242\end{ctypedesc}
243
244\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
245 This pointer is initialized to point to an array of \ctype{struct
246 _frozen} records, terminated by one whose members are all \NULL{} or
247 zero. When a frozen module is imported, it is searched in this
248 table. Third-party code could play tricks with this to provide a
249 dynamically created collection of frozen modules.
250\end{cvardesc}
251
252\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
253 void (*initfunc)(void)}
254 Add a single module to the existing table of built-in modules. This
255 is a convenience wrapper around
256 \cfunction{PyImport_ExtendInittab()}, returning \code{-1} if the
257 table could not be extended. The new module can be imported by the
258 name \var{name}, and uses the function \var{initfunc} as the
259 initialization function called on the first attempted import. This
260 should be called before \cfunction{Py_Initialize()}.
261\end{cfuncdesc}
262
263\begin{ctypedesc}[_inittab]{struct _inittab}
264 Structure describing a single entry in the list of built-in
265 modules. Each of these structures gives the name and initialization
266 function for a module built into the interpreter. Programs which
267 embed Python may use an array of these structures in conjunction
268 with \cfunction{PyImport_ExtendInittab()} to provide additional
269 built-in modules. The structure is defined in
270 \file{Include/import.h} as:
271
272\begin{verbatim}
273struct _inittab {
274 char *name;
275 void (*initfunc)(void);
276};
277\end{verbatim}
278\end{ctypedesc}
279
280\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
281 Add a collection of modules to the table of built-in modules. The
282 \var{newtab} array must end with a sentinel entry which contains
283 \NULL{} for the \member{name} field; failure to provide the sentinel
284 value can result in a memory fault. Returns \code{0} on success or
285 \code{-1} if insufficient memory could be allocated to extend the
286 internal table. In the event of failure, no modules are added to
287 the internal table. This should be called before
288 \cfunction{Py_Initialize()}.
289\end{cfuncdesc}
290
291
Fred Drake0fae49f2001-10-14 04:45:51 +0000292\section{Data marshalling support \label{marshalling-utils}}
293
294These routines allow C code to work with serialized objects using the
295same data format as the \module{marshal} module. There are functions
296to write data into the serialization format, and additional functions
297that can be used to read the data back. Files used to store marshalled
298data must be opened in binary mode.
299
300Numeric values are stored with the least significant byte first.
301
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000302The module supports two versions of the data format: version 0 is the
303historical version, version 1 (new in Python 2.4) shares interned
304strings in the file, and upon unmarshalling. \var{Py_MARSHAL_VERSION}
305indicates the current file format (currently 1).
306
307\begin{cfuncdesc}{void}{PyMarshal_WriteLongToFile}{long value, FILE *file, int version}
Fred Drake0fae49f2001-10-14 04:45:51 +0000308 Marshal a \ctype{long} integer, \var{value}, to \var{file}. This
309 will only write the least-significant 32 bits of \var{value};
310 regardless of the size of the native \ctype{long} type.
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000311
312 \versionchanged[\var{version} indicates the file format]{2.4}
Fred Drake0fae49f2001-10-14 04:45:51 +0000313\end{cfuncdesc}
314
Fred Drake0fae49f2001-10-14 04:45:51 +0000315\begin{cfuncdesc}{void}{PyMarshal_WriteObjectToFile}{PyObject *value,
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000316 FILE *file, int version}
Fred Drakeb0840172002-06-17 15:44:18 +0000317 Marshal a Python object, \var{value}, to \var{file}.
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000318
319 \versionchanged[\var{version} indicates the file format]{2.4}
Fred Drake0fae49f2001-10-14 04:45:51 +0000320\end{cfuncdesc}
321
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000322\begin{cfuncdesc}{PyObject*}{PyMarshal_WriteObjectToString}{PyObject *value, int version}
Fred Drake0fae49f2001-10-14 04:45:51 +0000323 Return a string object containing the marshalled representation of
324 \var{value}.
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000325
326 \versionchanged[\var{version} indicates the file format]{2.4}
Fred Drake0fae49f2001-10-14 04:45:51 +0000327\end{cfuncdesc}
328
329The following functions allow marshalled values to be read back in.
330
331XXX What about error detection? It appears that reading past the end
332of the file will always result in a negative numeric value (where
333that's relevant), but it's not clear that negative values won't be
334handled properly when there's no error. What's the right way to tell?
335Should only non-negative values be written using these routines?
336
337\begin{cfuncdesc}{long}{PyMarshal_ReadLongFromFile}{FILE *file}
338 Return a C \ctype{long} from the data stream in a \ctype{FILE*}
339 opened for reading. Only a 32-bit value can be read in using
340 this function, regardless of the native size of \ctype{long}.
341\end{cfuncdesc}
342
343\begin{cfuncdesc}{int}{PyMarshal_ReadShortFromFile}{FILE *file}
344 Return a C \ctype{short} from the data stream in a \ctype{FILE*}
345 opened for reading. Only a 16-bit value can be read in using
Fred Drakeb0840172002-06-17 15:44:18 +0000346 this function, regardless of the native size of \ctype{short}.
Fred Drake0fae49f2001-10-14 04:45:51 +0000347\end{cfuncdesc}
348
349\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromFile}{FILE *file}
350 Return a Python object from the data stream in a \ctype{FILE*}
351 opened for reading. On error, sets the appropriate exception
352 (\exception{EOFError} or \exception{TypeError}) and returns \NULL.
353\end{cfuncdesc}
354
355\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadLastObjectFromFile}{FILE *file}
356 Return a Python object from the data stream in a \ctype{FILE*}
357 opened for reading. Unlike
358 \cfunction{PyMarshal_ReadObjectFromFile()}, this function assumes
359 that no further objects will be read from the file, allowing it to
360 aggressively load file data into memory so that the de-serialization
361 can operate from data in memory rather than reading a byte at a time
362 from the file. Only use these variant if you are certain that you
363 won't be reading anything else from the file. On error, sets the
364 appropriate exception (\exception{EOFError} or
365 \exception{TypeError}) and returns \NULL.
366\end{cfuncdesc}
367
368\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromString}{char *string,
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000369 Py_ssize_t len}
Fred Drake0fae49f2001-10-14 04:45:51 +0000370 Return a Python object from the data stream in a character buffer
371 containing \var{len} bytes pointed to by \var{string}. On error,
372 sets the appropriate exception (\exception{EOFError} or
373 \exception{TypeError}) and returns \NULL.
374\end{cfuncdesc}
375
376
Fred Drake3adf79e2001-10-12 19:01:43 +0000377\section{Parsing arguments and building values
378 \label{arg-parsing}}
379
380These functions are useful when creating your own extensions functions
381and methods. Additional information and examples are available in
382\citetitle[../ext/ext.html]{Extending and Embedding the Python
383Interpreter}.
384
Fred Drake68304cc2002-04-05 23:01:14 +0000385The first three of these functions described,
386\cfunction{PyArg_ParseTuple()},
387\cfunction{PyArg_ParseTupleAndKeywords()}, and
388\cfunction{PyArg_Parse()}, all use \emph{format strings} which are
389used to tell the function about the expected arguments. The format
390strings use the same syntax for each of these functions.
391
392A format string consists of zero or more ``format units.'' A format
393unit describes one Python object; it is usually a single character or
394a parenthesized sequence of format units. With a few exceptions, a
395format unit that is not a parenthesized sequence normally corresponds
396to a single address argument to these functions. In the following
397description, the quoted form is the format unit; the entry in (round)
398parentheses is the Python object type that matches the format unit;
399and the entry in [square] brackets is the type of the C variable(s)
400whose address should be passed.
401
402\begin{description}
Brett Cannond88471f2004-07-01 20:55:42 +0000403 \item[\samp{s} (string or Unicode object) {[const char *]}]
Fred Drake68304cc2002-04-05 23:01:14 +0000404 Convert a Python string or Unicode object to a C pointer to a
405 character string. You must not provide storage for the string
406 itself; a pointer to an existing string is stored into the character
407 pointer variable whose address you pass. The C string is
408 NUL-terminated. The Python string must not contain embedded NUL
409 bytes; if it does, a \exception{TypeError} exception is raised.
410 Unicode objects are converted to C strings using the default
411 encoding. If this conversion fails, a \exception{UnicodeError} is
412 raised.
413
414 \item[\samp{s\#} (string, Unicode or any read buffer compatible object)
Brett Cannond88471f2004-07-01 20:55:42 +0000415 {[const char *, int]}]
Fred Drake68304cc2002-04-05 23:01:14 +0000416 This variant on \samp{s} stores into two C variables, the first one
417 a pointer to a character string, the second one its length. In this
418 case the Python string may contain embedded null bytes. Unicode
419 objects pass back a pointer to the default encoded string version of
420 the object if such a conversion is possible. All other read-buffer
421 compatible objects pass back a reference to the raw internal data
422 representation.
423
Walter Dörwald612344f2007-05-04 19:28:21 +0000424 \item[\samp{y} (bytes object)
425 {[const char *]}]
426 This variant on \samp{s} convert a Python bytes object to a C pointer to a
427 character string. The bytes object must not contain embedded NUL bytes;
428 if it does, a \exception{TypeError} exception is raised.
429
430 \item[\samp{y\#} (bytes object)
431 {[const char *, int]}]
432 This variant on \samp{s#} stores into two C variables, the first one
433 a pointer to a character string, the second one its length. This only
434 accepts bytes objects.
435
Brett Cannond88471f2004-07-01 20:55:42 +0000436 \item[\samp{z} (string or \code{None}) {[const char *]}]
Fred Drake68304cc2002-04-05 23:01:14 +0000437 Like \samp{s}, but the Python object may also be \code{None}, in
438 which case the C pointer is set to \NULL.
439
440 \item[\samp{z\#} (string or \code{None} or any read buffer
Brett Cannond88471f2004-07-01 20:55:42 +0000441 compatible object) {[const char *, int]}]
Fred Drake68304cc2002-04-05 23:01:14 +0000442 This is to \samp{s\#} as \samp{z} is to \samp{s}.
443
444 \item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
445 Convert a Python Unicode object to a C pointer to a NUL-terminated
446 buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is
447 no need to provide storage for the Unicode data buffer; a pointer to
448 the existing Unicode data is stored into the \ctype{Py_UNICODE}
449 pointer variable whose address you pass.
450
451 \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
452 This variant on \samp{u} stores into two C variables, the first one
453 a pointer to a Unicode data buffer, the second one its length.
454 Non-Unicode objects are handled by interpreting their read-buffer
455 pointer as pointer to a \ctype{Py_UNICODE} array.
456
457 \item[\samp{es} (string, Unicode object or character buffer
458 compatible object) {[const char *encoding, char **buffer]}]
459 This variant on \samp{s} is used for encoding Unicode and objects
460 convertible to Unicode into a character buffer. It only works for
461 encoded data without embedded NUL bytes.
462
463 This format requires two arguments. The first is only used as
Brett Cannond88471f2004-07-01 20:55:42 +0000464 input, and must be a \ctype{const char*} which points to the name of an
Fred Drake68304cc2002-04-05 23:01:14 +0000465 encoding as a NUL-terminated string, or \NULL, in which case the
466 default encoding is used. An exception is raised if the named
467 encoding is not known to Python. The second argument must be a
468 \ctype{char**}; the value of the pointer it references will be set
469 to a buffer with the contents of the argument text. The text will
470 be encoded in the encoding specified by the first argument.
471
472 \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
473 size, copy the encoded data into this buffer and adjust
474 \var{*buffer} to reference the newly allocated storage. The caller
475 is responsible for calling \cfunction{PyMem_Free()} to free the
476 allocated buffer after use.
477
478 \item[\samp{et} (string, Unicode object or character buffer
479 compatible object) {[const char *encoding, char **buffer]}]
480 Same as \samp{es} except that 8-bit string objects are passed
481 through without recoding them. Instead, the implementation assumes
482 that the string object uses the encoding passed in as parameter.
483
484 \item[\samp{es\#} (string, Unicode object or character buffer compatible
485 object) {[const char *encoding, char **buffer, int *buffer_length]}]
486 This variant on \samp{s\#} is used for encoding Unicode and objects
487 convertible to Unicode into a character buffer. Unlike the
488 \samp{es} format, this variant allows input data which contains NUL
489 characters.
490
491 It requires three arguments. The first is only used as input, and
Brett Cannond88471f2004-07-01 20:55:42 +0000492 must be a \ctype{const char*} which points to the name of an encoding as a
Fred Drake68304cc2002-04-05 23:01:14 +0000493 NUL-terminated string, or \NULL, in which case the default encoding
494 is used. An exception is raised if the named encoding is not known
495 to Python. The second argument must be a \ctype{char**}; the value
496 of the pointer it references will be set to a buffer with the
497 contents of the argument text. The text will be encoded in the
498 encoding specified by the first argument. The third argument must
499 be a pointer to an integer; the referenced integer will be set to
500 the number of bytes in the output buffer.
501
502 There are two modes of operation:
503
504 If \var{*buffer} points a \NULL{} pointer, the function will
505 allocate a buffer of the needed size, copy the encoded data into
506 this buffer and set \var{*buffer} to reference the newly allocated
507 storage. The caller is responsible for calling
508 \cfunction{PyMem_Free()} to free the allocated buffer after usage.
509
510 If \var{*buffer} points to a non-\NULL{} pointer (an already
511 allocated buffer), \cfunction{PyArg_ParseTuple()} will use this
512 location as the buffer and interpret the initial value of
513 \var{*buffer_length} as the buffer size. It will then copy the
514 encoded data into the buffer and NUL-terminate it. If the buffer
515 is not large enough, a \exception{ValueError} will be set.
516
517 In both cases, \var{*buffer_length} is set to the length of the
518 encoded data without the trailing NUL byte.
519
520 \item[\samp{et\#} (string, Unicode object or character buffer compatible
521 object) {[const char *encoding, char **buffer]}]
522 Same as \samp{es\#} except that string objects are passed through
523 without recoding them. Instead, the implementation assumes that the
524 string object uses the encoding passed in as parameter.
525
526 \item[\samp{b} (integer) {[char]}]
527 Convert a Python integer to a tiny int, stored in a C \ctype{char}.
528
Thomas Heller42a11722003-04-23 19:27:35 +0000529 \item[\samp{B} (integer) {[unsigned char]}]
530 Convert a Python integer to a tiny int without overflow checking,
531 stored in a C \ctype{unsigned char}. \versionadded{2.3}
532
Fred Drake68304cc2002-04-05 23:01:14 +0000533 \item[\samp{h} (integer) {[short int]}]
534 Convert a Python integer to a C \ctype{short int}.
535
Thomas Heller42a11722003-04-23 19:27:35 +0000536 \item[\samp{H} (integer) {[unsigned short int]}]
537 Convert a Python integer to a C \ctype{unsigned short int}, without
538 overflow checking. \versionadded{2.3}
539
Fred Drake68304cc2002-04-05 23:01:14 +0000540 \item[\samp{i} (integer) {[int]}]
541 Convert a Python integer to a plain C \ctype{int}.
542
Thomas Heller42a11722003-04-23 19:27:35 +0000543 \item[\samp{I} (integer) {[unsigned int]}]
544 Convert a Python integer to a C \ctype{unsigned int}, without
545 overflow checking. \versionadded{2.3}
546
Fred Drake68304cc2002-04-05 23:01:14 +0000547 \item[\samp{l} (integer) {[long int]}]
548 Convert a Python integer to a C \ctype{long int}.
549
Thomas Heller42a11722003-04-23 19:27:35 +0000550 \item[\samp{k} (integer) {[unsigned long]}]
Georg Brandl0e032722005-07-17 20:05:25 +0000551 Convert a Python integer or long integer to a C \ctype{unsigned long} without
Thomas Heller42a11722003-04-23 19:27:35 +0000552 overflow checking. \versionadded{2.3}
553
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000554 \item[\samp{L} (integer) {[PY_LONG_LONG]}]
Fred Drake68304cc2002-04-05 23:01:14 +0000555 Convert a Python integer to a C \ctype{long long}. This format is
556 only available on platforms that support \ctype{long long} (or
557 \ctype{_int64} on Windows).
558
Thomas Heller42a11722003-04-23 19:27:35 +0000559 \item[\samp{K} (integer) {[unsigned PY_LONG_LONG]}]
Georg Brandl0e032722005-07-17 20:05:25 +0000560 Convert a Python integer or long integer to a C \ctype{unsigned long long}
Thomas Heller42a11722003-04-23 19:27:35 +0000561 without overflow checking. This format is only available on
562 platforms that support \ctype{unsigned long long} (or
563 \ctype{unsigned _int64} on Windows). \versionadded{2.3}
564
Martin v. Löwis3b197542006-03-01 05:47:11 +0000565 \item[\samp{n} (integer) {[Py_ssize_t]}]
566 Convert a Python integer or long integer to a C \ctype{Py_ssize_t}.
567 \versionadded{2.5}
568
Fred Drake68304cc2002-04-05 23:01:14 +0000569 \item[\samp{c} (string of length 1) {[char]}]
570 Convert a Python character, represented as a string of length 1, to
571 a C \ctype{char}.
572
573 \item[\samp{f} (float) {[float]}]
574 Convert a Python floating point number to a C \ctype{float}.
575
576 \item[\samp{d} (float) {[double]}]
577 Convert a Python floating point number to a C \ctype{double}.
578
579 \item[\samp{D} (complex) {[Py_complex]}]
580 Convert a Python complex number to a C \ctype{Py_complex} structure.
581
582 \item[\samp{O} (object) {[PyObject *]}]
583 Store a Python object (without any conversion) in a C object
584 pointer. The C program thus receives the actual object that was
585 passed. The object's reference count is not increased. The pointer
586 stored is not \NULL.
587
588 \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
589 Store a Python object in a C object pointer. This is similar to
590 \samp{O}, but takes two C arguments: the first is the address of a
591 Python type object, the second is the address of the C variable (of
592 type \ctype{PyObject*}) into which the object pointer is stored. If
593 the Python object does not have the required type,
594 \exception{TypeError} is raised.
595
596 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
597 Convert a Python object to a C variable through a \var{converter}
598 function. This takes two arguments: the first is a function, the
599 second is the address of a C variable (of arbitrary type), converted
600 to \ctype{void *}. The \var{converter} function in turn is called
601 as follows:
602
603 \var{status}\code{ = }\var{converter}\code{(}\var{object},
604 \var{address}\code{);}
605
606 where \var{object} is the Python object to be converted and
607 \var{address} is the \ctype{void*} argument that was passed to the
608 \cfunction{PyArg_Parse*()} function. The returned \var{status}
609 should be \code{1} for a successful conversion and \code{0} if the
610 conversion has failed. When the conversion fails, the
611 \var{converter} function should raise an exception.
612
613 \item[\samp{S} (string) {[PyStringObject *]}]
614 Like \samp{O} but requires that the Python object is a string
615 object. Raises \exception{TypeError} if the object is not a string
616 object. The C variable may also be declared as \ctype{PyObject*}.
617
618 \item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
619 Like \samp{O} but requires that the Python object is a Unicode
620 object. Raises \exception{TypeError} if the object is not a Unicode
621 object. The C variable may also be declared as \ctype{PyObject*}.
622
623 \item[\samp{t\#} (read-only character buffer) {[char *, int]}]
624 Like \samp{s\#}, but accepts any object which implements the
625 read-only buffer interface. The \ctype{char*} variable is set to
626 point to the first byte of the buffer, and the \ctype{int} is set to
627 the length of the buffer. Only single-segment buffer objects are
628 accepted; \exception{TypeError} is raised for all others.
629
630 \item[\samp{w} (read-write character buffer) {[char *]}]
631 Similar to \samp{s}, but accepts any object which implements the
632 read-write buffer interface. The caller must determine the length
633 of the buffer by other means, or use \samp{w\#} instead. Only
634 single-segment buffer objects are accepted; \exception{TypeError} is
635 raised for all others.
636
637 \item[\samp{w\#} (read-write character buffer) {[char *, int]}]
638 Like \samp{s\#}, but accepts any object which implements the
639 read-write buffer interface. The \ctype{char *} variable is set to
640 point to the first byte of the buffer, and the \ctype{int} is set to
641 the length of the buffer. Only single-segment buffer objects are
642 accepted; \exception{TypeError} is raised for all others.
643
644 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
645 The object must be a Python sequence whose length is the number of
646 format units in \var{items}. The C arguments must correspond to the
647 individual format units in \var{items}. Format units for sequences
648 may be nested.
649
650 \note{Prior to Python version 1.5.2, this format specifier only
651 accepted a tuple containing the individual parameters, not an
652 arbitrary sequence. Code which previously caused
653 \exception{TypeError} to be raised here may now proceed without an
654 exception. This is not expected to be a problem for existing code.}
655\end{description}
656
657It is possible to pass Python long integers where integers are
658requested; however no proper range checking is done --- the most
659significant bits are silently truncated when the receiving field is
660too small to receive the value (actually, the semantics are inherited
661from downcasts in C --- your mileage may vary).
662
663A few other characters have a meaning in a format string. These may
664not occur inside nested parentheses. They are:
665
666\begin{description}
667 \item[\samp{|}]
668 Indicates that the remaining arguments in the Python argument list
669 are optional. The C variables corresponding to optional arguments
670 should be initialized to their default value --- when an optional
671 argument is not specified, \cfunction{PyArg_ParseTuple()} does not
672 touch the contents of the corresponding C variable(s).
673
674 \item[\samp{:}]
675 The list of format units ends here; the string after the colon is
676 used as the function name in error messages (the ``associated
677 value'' of the exception that \cfunction{PyArg_ParseTuple()}
678 raises).
679
680 \item[\samp{;}]
681 The list of format units ends here; the string after the semicolon
682 is used as the error message \emph{instead} of the default error
683 message. Clearly, \samp{:} and \samp{;} mutually exclude each
684 other.
685\end{description}
686
687Note that any Python object references which are provided to the
688caller are \emph{borrowed} references; do not decrement their
689reference count!
690
691Additional arguments passed to these functions must be addresses of
692variables whose type is determined by the format string; these are
693used to store values from the input tuple. There are a few cases, as
694described in the list of format units above, where these parameters
695are used as input values; they should match what is specified for the
696corresponding format unit in that case.
697
698For the conversion to succeed, the \var{arg} object must match the
699format and the format must be exhausted. On success, the
700\cfunction{PyArg_Parse*()} functions return true, otherwise they
701return false and raise an appropriate exception.
702
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000703\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, const char *format,
Fred Drake3adf79e2001-10-12 19:01:43 +0000704 \moreargs}
705 Parse the parameters of a function that takes only positional
706 parameters into local variables. Returns true on success; on
Fred Drake68304cc2002-04-05 23:01:14 +0000707 failure, it returns false and raises the appropriate exception.
Fred Drake3adf79e2001-10-12 19:01:43 +0000708\end{cfuncdesc}
709
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000710\begin{cfuncdesc}{int}{PyArg_VaParse}{PyObject *args, const char *format,
Brett Cannon711e7d92004-07-10 22:20:32 +0000711 va_list vargs}
712 Identical to \cfunction{PyArg_ParseTuple()}, except that it accepts a
713 va_list rather than a variable number of arguments.
714\end{cfuncdesc}
715
Fred Drake3adf79e2001-10-12 19:01:43 +0000716\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args,
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000717 PyObject *kw, const char *format, char *keywords[],
Fred Drake3adf79e2001-10-12 19:01:43 +0000718 \moreargs}
719 Parse the parameters of a function that takes both positional and
720 keyword parameters into local variables. Returns true on success;
721 on failure, it returns false and raises the appropriate exception.
Fred Drake3adf79e2001-10-12 19:01:43 +0000722\end{cfuncdesc}
723
Brett Cannon711e7d92004-07-10 22:20:32 +0000724\begin{cfuncdesc}{int}{PyArg_VaParseTupleAndKeywords}{PyObject *args,
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000725 PyObject *kw, const char *format, char *keywords[],
Brett Cannon711e7d92004-07-10 22:20:32 +0000726 va_list vargs}
727 Identical to \cfunction{PyArg_ParseTupleAndKeywords()}, except that it
728 accepts a va_list rather than a variable number of arguments.
729\end{cfuncdesc}
730
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000731\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, const char *format,
Fred Drake3adf79e2001-10-12 19:01:43 +0000732 \moreargs}
733 Function used to deconstruct the argument lists of ``old-style''
734 functions --- these are functions which use the
735 \constant{METH_OLDARGS} parameter parsing method. This is not
736 recommended for use in parameter parsing in new code, and most code
737 in the standard interpreter has been modified to no longer use this
738 for that purpose. It does remain a convenient way to decompose
739 other tuples, however, and may continue to be used for that
740 purpose.
741\end{cfuncdesc}
742
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000743\begin{cfuncdesc}{int}{PyArg_UnpackTuple}{PyObject *args, const char *name,
744 Py_ssize_t min, Py_ssize_t max, \moreargs}
Fred Drakec84f2c52001-10-23 21:10:18 +0000745 A simpler form of parameter retrieval which does not use a format
746 string to specify the types of the arguments. Functions which use
747 this method to retrieve their parameters should be declared as
748 \constant{METH_VARARGS} in function or method tables. The tuple
749 containing the actual parameters should be passed as \var{args}; it
750 must actually be a tuple. The length of the tuple must be at least
751 \var{min} and no more than \var{max}; \var{min} and \var{max} may be
752 equal. Additional arguments must be passed to the function, each of
753 which should be a pointer to a \ctype{PyObject*} variable; these
754 will be filled in with the values from \var{args}; they will contain
755 borrowed references. The variables which correspond to optional
756 parameters not given by \var{args} will not be filled in; these
757 should be initialized by the caller.
758 This function returns true on success and false if \var{args} is not
759 a tuple or contains the wrong number of elements; an exception will
760 be set if there was a failure.
761
762 This is an example of the use of this function, taken from the
763 sources for the \module{_weakref} helper module for weak references:
764
765\begin{verbatim}
766static PyObject *
767weakref_ref(PyObject *self, PyObject *args)
768{
769 PyObject *object;
770 PyObject *callback = NULL;
771 PyObject *result = NULL;
772
773 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
774 result = PyWeakref_NewRef(object, callback);
775 }
776 return result;
777}
778\end{verbatim}
779
780 The call to \cfunction{PyArg_UnpackTuple()} in this example is
781 entirely equivalent to this call to \cfunction{PyArg_ParseTuple()}:
782
783\begin{verbatim}
784PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
785\end{verbatim}
786
787 \versionadded{2.2}
788\end{cfuncdesc}
789
Martin v. Löwis29fafd82006-03-01 05:16:03 +0000790\begin{cfuncdesc}{PyObject*}{Py_BuildValue}{const char *format,
Fred Drake3adf79e2001-10-12 19:01:43 +0000791 \moreargs}
792 Create a new value based on a format string similar to those
793 accepted by the \cfunction{PyArg_Parse*()} family of functions and a
794 sequence of values. Returns the value or \NULL{} in the case of an
Fred Drake68304cc2002-04-05 23:01:14 +0000795 error; an exception will be raised if \NULL{} is returned.
796
797 \cfunction{Py_BuildValue()} does not always build a tuple. It
798 builds a tuple only if its format string contains two or more format
799 units. If the format string is empty, it returns \code{None}; if it
800 contains exactly one format unit, it returns whatever object is
801 described by that format unit. To force it to return a tuple of
802 size 0 or one, parenthesize the format string.
803
804 When memory buffers are passed as parameters to supply data to build
805 objects, as for the \samp{s} and \samp{s\#} formats, the required
806 data is copied. Buffers provided by the caller are never referenced
807 by the objects created by \cfunction{Py_BuildValue()}. In other
808 words, if your code invokes \cfunction{malloc()} and passes the
809 allocated memory to \cfunction{Py_BuildValue()}, your code is
810 responsible for calling \cfunction{free()} for that memory once
811 \cfunction{Py_BuildValue()} returns.
812
813 In the following description, the quoted form is the format unit;
814 the entry in (round) parentheses is the Python object type that the
815 format unit will return; and the entry in [square] brackets is the
816 type of the C value(s) to be passed.
817
818 The characters space, tab, colon and comma are ignored in format
819 strings (but not within format units such as \samp{s\#}). This can
820 be used to make long format strings a tad more readable.
821
822 \begin{description}
823 \item[\samp{s} (string) {[char *]}]
824 Convert a null-terminated C string to a Python object. If the C
825 string pointer is \NULL, \code{None} is used.
826
827 \item[\samp{s\#} (string) {[char *, int]}]
828 Convert a C string and its length to a Python object. If the C
829 string pointer is \NULL, the length is ignored and \code{None} is
830 returned.
831
832 \item[\samp{z} (string or \code{None}) {[char *]}]
833 Same as \samp{s}.
834
835 \item[\samp{z\#} (string or \code{None}) {[char *, int]}]
836 Same as \samp{s\#}.
837
838 \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
Tim Peterscfd575d2004-08-02 03:46:45 +0000839 Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4)
840 data to a Python Unicode object. If the Unicode buffer pointer
Martin v. Löwis9bc4f2d2004-06-03 09:55:28 +0000841 is \NULL, \code{None} is returned.
Fred Drake68304cc2002-04-05 23:01:14 +0000842
843 \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
Tim Peterscfd575d2004-08-02 03:46:45 +0000844 Convert a Unicode (UCS-2 or UCS-4) data buffer and its length
845 to a Python Unicode object. If the Unicode buffer pointer
Martin v. Löwis9bc4f2d2004-06-03 09:55:28 +0000846 is \NULL, the length is ignored and \code{None} is returned.
Fred Drake68304cc2002-04-05 23:01:14 +0000847
Walter Dörwaldd2034312007-05-18 16:29:38 +0000848 \item[\samp{U} (string) {[char *]}]
849 Convert a null-terminated C string to a Python unicode object.
850 If the C string pointer is \NULL, \code{None} is used.
851
852 \item[\samp{U\#} (string) {[char *, int]}]
853 Convert a C string and its length to a Python unicode object.
854 If the C string pointer is \NULL, the length is ignored and \code{None}
855 is returned.
856
Fred Drake68304cc2002-04-05 23:01:14 +0000857 \item[\samp{i} (integer) {[int]}]
858 Convert a plain C \ctype{int} to a Python integer object.
859
860 \item[\samp{b} (integer) {[char]}]
Georg Brandlf06e30a2005-11-24 15:37:42 +0000861 Convert a plain C \ctype{char} to a Python integer object.
Fred Drake68304cc2002-04-05 23:01:14 +0000862
863 \item[\samp{h} (integer) {[short int]}]
Georg Brandlf06e30a2005-11-24 15:37:42 +0000864 Convert a plain C \ctype{short int} to a Python integer object.
Fred Drake68304cc2002-04-05 23:01:14 +0000865
866 \item[\samp{l} (integer) {[long int]}]
867 Convert a C \ctype{long int} to a Python integer object.
868
Georg Brandlf06e30a2005-11-24 15:37:42 +0000869 \item[\samp{B} (integer) {[unsigned char]}]
870 Convert a C \ctype{unsigned char} to a Python integer object.
871
872 \item[\samp{H} (integer) {[unsigned short int]}]
873 Convert a C \ctype{unsigned short int} to a Python integer object.
874
875 \item[\samp{I} (integer/long) {[unsigned int]}]
876 Convert a C \ctype{unsigned int} to a Python integer object
877 or a Python long integer object, if it is larger than \code{sys.maxint}.
878
879 \item[\samp{k} (integer/long) {[unsigned long]}]
880 Convert a C \ctype{unsigned long} to a Python integer object
881 or a Python long integer object, if it is larger than \code{sys.maxint}.
882
883 \item[\samp{L} (long) {[PY_LONG_LONG]}]
884 Convert a C \ctype{long long} to a Python long integer object. Only
885 available on platforms that support \ctype{long long}.
886
887 \item[\samp{K} (long) {[unsigned PY_LONG_LONG]}]
888 Convert a C \ctype{unsigned long long} to a Python long integer object.
889 Only available on platforms that support \ctype{unsigned long long}.
890
Martin v. Löwis3b197542006-03-01 05:47:11 +0000891 \item[\samp{n} (int) {[Py_ssize_t]}]
Fredrik Lundh1f2dac52006-03-01 12:43:53 +0000892 Convert a C \ctype{Py_ssize_t} to a Python integer or long integer.
Martin v. Löwis3b197542006-03-01 05:47:11 +0000893 \versionadded{2.5}
894
Fred Drake68304cc2002-04-05 23:01:14 +0000895 \item[\samp{c} (string of length 1) {[char]}]
896 Convert a C \ctype{int} representing a character to a Python
897 string of length 1.
898
899 \item[\samp{d} (float) {[double]}]
900 Convert a C \ctype{double} to a Python floating point number.
901
902 \item[\samp{f} (float) {[float]}]
903 Same as \samp{d}.
904
905 \item[\samp{D} (complex) {[Py_complex *]}]
906 Convert a C \ctype{Py_complex} structure to a Python complex
907 number.
908
909 \item[\samp{O} (object) {[PyObject *]}]
910 Pass a Python object untouched (except for its reference count,
911 which is incremented by one). If the object passed in is a
912 \NULL{} pointer, it is assumed that this was caused because the
913 call producing the argument found an error and set an exception.
914 Therefore, \cfunction{Py_BuildValue()} will return \NULL{} but
915 won't raise an exception. If no exception has been raised yet,
916 \exception{SystemError} is set.
917
918 \item[\samp{S} (object) {[PyObject *]}]
919 Same as \samp{O}.
920
Fred Drake68304cc2002-04-05 23:01:14 +0000921 \item[\samp{N} (object) {[PyObject *]}]
922 Same as \samp{O}, except it doesn't increment the reference count
923 on the object. Useful when the object is created by a call to an
924 object constructor in the argument list.
925
926 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
927 Convert \var{anything} to a Python object through a
928 \var{converter} function. The function is called with
929 \var{anything} (which should be compatible with \ctype{void *}) as
930 its argument and should return a ``new'' Python object, or \NULL{}
931 if an error occurred.
932
933 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
934 Convert a sequence of C values to a Python tuple with the same
935 number of items.
936
937 \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
938 Convert a sequence of C values to a Python list with the same
939 number of items.
940
941 \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
942 Convert a sequence of C values to a Python dictionary. Each pair
943 of consecutive C values adds one item to the dictionary, serving
944 as key and value, respectively.
945
946 \end{description}
947
948 If there is an error in the format string, the
949 \exception{SystemError} exception is set and \NULL{} returned.
Fred Drake3adf79e2001-10-12 19:01:43 +0000950\end{cfuncdesc}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952\section{String conversion and formatting \label{string-formatting}}
953
954Functions for number conversion and formatted string output.
955
956\begin{cfuncdesc}{int}{PyOS_snprintf}{char *str, size_t size,
957 const char *format, \moreargs}
958Output not more than \var{size} bytes to \var{str} according to the format
959string \var{format} and the extra arguments. See the \UNIX{} man
960page \manpage{snprintf}{2}.
961\end{cfuncdesc}
962
963\begin{cfuncdesc}{int}{PyOS_vsnprintf}{char *str, size_t size,
964 const char *format, va_list va}
965Output not more than \var{size} bytes to \var{str} according to the format
966string \var{format} and the variable argument list \var{va}. \UNIX{}
967man page \manpage{vsnprintf}{2}.
968\end{cfuncdesc}
969
970\cfunction{PyOS_snprintf} and \cfunction{PyOS_vsnprintf} wrap the
971Standard C library functions \cfunction{snprintf()} and
972\cfunction{vsnprintf()}. Their purpose is to guarantee consistent
973behavior in corner cases, which the Standard C functions do not.
974
975The wrappers ensure that \var{str}[\var{size}-1] is always
976\character{\textbackslash0} upon return. They never write more than
977\var{size} bytes (including the trailing \character{\textbackslash0}
978into str. Both functions require that \code{\var{str} != NULL},
979\code{\var{size} > 0} and \code{\var{format} != NULL}.
980
981If the platform doesn't have \cfunction{vsnprintf()} and the buffer
982size needed to avoid truncation exceeds \var{size} by more than 512
983bytes, Python aborts with a \var{Py_FatalError}.
984
985The return value (\var{rv}) for these functions should be interpreted
986as follows:
987
988\begin{itemize}
989
990\item When \code{0 <= \var{rv} < \var{size}}, the output conversion
991 was successful and \var{rv} characters were written to \var{str}
992 (excluding the trailing \character{\textbackslash0} byte at
993 \var{str}[\var{rv}]).
994
995\item When \code{\var{rv} >= \var{size}}, the output conversion was
996 truncated and a buffer with \code{\var{rv} + 1} bytes would have
997 been needed to succeed. \var{str}[\var{size}-1] is
998 \character{\textbackslash0} in this case.
999
1000\item When \code{\var{rv} < 0}, ``something bad happened.''
1001 \var{str}[\var{size}-1] is \character{\textbackslash0} in this case
1002 too, but the rest of \var{str} is undefined. The exact cause of the
1003 error depends on the underlying platform.
1004
1005\end{itemize}
1006
1007The following functions provide locale-independent string to number
1008conversions.
1009
1010\begin{cfuncdesc}{double}{PyOS_ascii_strtod}{const char *nptr, char **endptr}
1011Convert a string to a \ctype{double}. This function behaves like the
1012Standard C function \cfunction{strtod()} does in the C locale. It does
1013this without changing the current locale, since that would not be
1014thread-safe.
1015
1016\cfunction{PyOS_ascii_strtod} should typically be used for reading
1017configuration files or other non-user input that should be locale
1018independent. \versionadded{2.4}
1019
1020See the \UNIX{} man page \manpage{strtod}{2} for details.
1021
1022\end{cfuncdesc}
1023
1024\begin{cfuncdesc}{char *}{PyOS_ascii_formatd}{char *buffer, size_t buf_len,
1025 const char *format, double d}
1026Convert a \ctype{double} to a string using the \character{.} as the
1027decimal separator. \var{format} is a \cfunction{printf()}-style format
1028string specifying the number format. Allowed conversion characters are
1029\character{e}, \character{E}, \character{f}, \character{F},
1030\character{g} and \character{G}.
1031
1032The return value is a pointer to \var{buffer} with the converted
1033string or NULL if the conversion failed. \versionadded{2.4}
1034\end{cfuncdesc}
1035
1036\begin{cfuncdesc}{double}{PyOS_ascii_atof}{const char *nptr}
1037Convert a string to a \ctype{double} in a locale-independent
1038way. \versionadded{2.4}
1039
1040See the \UNIX{} man page \manpage{atof}{2} for details.
1041\end{cfuncdesc}