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