rest25/c-api/utilities.rst => rest262/c-api/utilities.rst
6*********
7Utilities
8*********
9
10The functions in this chapter perform various utility tasks, ranging from
11helping C code be more portable across platforms, using Python modules from C,
12and parsing function arguments and constructing Python values from C values.
13
n14+.. toctree::
14
t15-.. _os:
t16+   sys.rst
16- 
17+   import.rst
17-Operating System Utilities
18+   marshal.rst
18-==========================
19+   arg.rst
19- 
20+   conversion.rst
20- 
21+   reflection.rst
21-.. cfunction:: int Py_FdIsInteractive(FILE *fp, const char *filename)
22- 
23-   Return true (nonzero) if the standard I/O file *fp* with name *filename* is
24-   deemed interactive.  This is the case for files for which ``isatty(fileno(fp))``
25-   is true.  If the global flag :cdata:`Py_InteractiveFlag` is true, this function
26-   also returns true if the *filename* pointer is *NULL* or if the name is equal to
27-   one of the strings ``'<stdin>'`` or ``'???'``.
28- 
29- 
30-.. cfunction:: long PyOS_GetLastModificationTime(char *filename)
31- 
32-   Return the time of last modification of the file *filename*. The result is
33-   encoded in the same way as the timestamp returned by the standard C library
34-   function :cfunc:`time`.
35- 
36- 
37-.. cfunction:: void PyOS_AfterFork()
38- 
39-   Function to update some internal state after a process fork; this should be
40-   called in the new process if the Python interpreter will continue to be used.
41-   If a new executable is loaded into the new process, this function does not need
42-   to be called.
43- 
44- 
45-.. cfunction:: int PyOS_CheckStack()
46- 
47-   Return true when the interpreter runs out of stack space.  This is a reliable
48-   check, but is only available when :const:`USE_STACKCHECK` is defined (currently
49-   on Windows using the Microsoft Visual C++ compiler).  :const:`USE_STACKCHECK`
50-   will be defined automatically; you should never change the definition in your
51-   own code.
52- 
53- 
54-.. cfunction:: PyOS_sighandler_t PyOS_getsig(int i)
55- 
56-   Return the current signal handler for signal *i*.  This is a thin wrapper around
57-   either :cfunc:`sigaction` or :cfunc:`signal`.  Do not call those functions
58-   directly! :ctype:`PyOS_sighandler_t` is a typedef alias for :ctype:`void
59-   (\*)(int)`.
60- 
61- 
62-.. cfunction:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
63- 
64-   Set the signal handler for signal *i* to be *h*; return the old signal handler.
65-   This is a thin wrapper around either :cfunc:`sigaction` or :cfunc:`signal`.  Do
66-   not call those functions directly!  :ctype:`PyOS_sighandler_t` is a typedef
67-   alias for :ctype:`void (\*)(int)`.
68- 
69- 
70-.. _processcontrol:
71- 
72-Process Control
73-===============
74- 
75- 
76-.. cfunction:: void Py_FatalError(const char *message)
77- 
78-   .. index:: single: abort()
79- 
80-   Print a fatal error message and kill the process.  No cleanup is performed.
81-   This function should only be invoked when a condition is detected that would
82-   make it dangerous to continue using the Python interpreter; e.g., when the
83-   object administration appears to be corrupted.  On Unix, the standard C library
84-   function :cfunc:`abort` is called which will attempt to produce a :file:`core`
85-   file.
86- 
87- 
88-.. cfunction:: void Py_Exit(int status)
89- 
90-   .. index::
91-      single: Py_Finalize()
92-      single: exit()
93- 
94-   Exit the current process.  This calls :cfunc:`Py_Finalize` and then calls the
95-   standard C library function ``exit(status)``.
96- 
97- 
98-.. cfunction:: int Py_AtExit(void (*func) ())
99- 
100-   .. index::
101-      single: Py_Finalize()
102-      single: cleanup functions
103- 
104-   Register a cleanup function to be called by :cfunc:`Py_Finalize`.  The cleanup
105-   function will be called with no arguments and should return no value.  At most
106-   32 cleanup functions can be registered.  When the registration is successful,
107-   :cfunc:`Py_AtExit` returns ``0``; on failure, it returns ``-1``.  The cleanup
108-   function registered last is called first. Each cleanup function will be called
109-   at most once.  Since Python's internal finalization will have completed before
110-   the cleanup function, no Python APIs should be called by *func*.
111- 
112- 
113-.. _importing:
114- 
115-Importing Modules
116-=================
117- 
118- 
119-.. cfunction:: PyObject* PyImport_ImportModule(const char *name)
120- 
121-   .. index::
122-      single: package variable; __all__
123-      single: __all__ (package variable)
124- 
125-   This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below,
126-   leaving the *globals* and *locals* arguments set to *NULL*.  When the *name*
127-   argument contains a dot (when it specifies a submodule of a package), the
128-   *fromlist* argument is set to the list ``['*']`` so that the return value is the
129-   named module rather than the top-level package containing it as would otherwise
130-   be the case.  (Unfortunately, this has an additional side effect when *name* in
131-   fact specifies a subpackage instead of a submodule: the submodules specified in
132-   the package's ``__all__`` variable are  loaded.)  Return a new reference to the
133-   imported module, or *NULL* with an exception set on failure.  Before Python 2.4,
134-   the module may still be created in the failure case --- examine ``sys.modules``
135-   to find out.  Starting with Python 2.4, a failing import of a module no longer
136-   leaves the module in ``sys.modules``.
137- 
138-   .. versionchanged:: 2.4
139-      failing imports remove incomplete module objects.
140- 
141-   .. index:: single: modules (in module sys)
142- 
143- 
144-.. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)
145- 
146-   .. index:: builtin: __import__
147- 
148-   Import a module.  This is best described by referring to the built-in Python
149-   function :func:`__import__`, as the standard :func:`__import__` function calls
150-   this function directly.
151- 
152-   The return value is a new reference to the imported module or top-level package,
153-   or *NULL* with an exception set on failure (before Python 2.4, the module may
154-   still be created in this case).  Like for :func:`__import__`, the return value
155-   when a submodule of a package was requested is normally the top-level package,
156-   unless a non-empty *fromlist* was given.
157- 
158-   .. versionchanged:: 2.4
159-      failing imports remove incomplete module objects.
160- 
161- 
162-.. cfunction:: PyObject* PyImport_Import(PyObject *name)
163- 
164-   .. index::
165-      module: rexec
166-      module: ihooks
167- 
168-   This is a higher-level interface that calls the current "import hook function".
169-   It invokes the :func:`__import__` function from the ``__builtins__`` of the
170-   current globals.  This means that the import is done using whatever import hooks
171-   are installed in the current environment, e.g. by :mod:`rexec` or :mod:`ihooks`.
172- 
173- 
174-.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m)
175- 
176-   .. index:: builtin: reload
177- 
178-   Reload a module.  This is best described by referring to the built-in Python
179-   function :func:`reload`, as the standard :func:`reload` function calls this
180-   function directly.  Return a new reference to the reloaded module, or *NULL*
181-   with an exception set on failure (the module still exists in this case).
182- 
183- 
184-.. cfunction:: PyObject* PyImport_AddModule(const char *name)
185- 
186-   Return the module object corresponding to a module name.  The *name* argument
187-   may be of the form ``package.module``. First check the modules dictionary if
188-   there's one there, and if not, create a new one and insert it in the modules
189-   dictionary. Return *NULL* with an exception set on failure.
190- 
191-   .. note::
192- 
193-      This function does not load or import the module; if the module wasn't already
194-      loaded, you will get an empty module object. Use :cfunc:`PyImport_ImportModule`
195-      or one of its variants to import a module.  Package structures implied by a
196-      dotted name for *name* are not created if not already present.
197- 
198- 
199-.. cfunction:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co)
200- 
201-   .. index:: builtin: compile
202- 
203-   Given a module name (possibly of the form ``package.module``) and a code object
204-   read from a Python bytecode file or obtained from the built-in function
205-   :func:`compile`, load the module.  Return a new reference to the module object,
206-   or *NULL* with an exception set if an error occurred.  Before Python 2.4, the
207-   module could still be created in error cases.  Starting with Python 2.4, *name*
208-   is removed from ``sys.modules`` in error cases, and even if *name* was already
209-   in ``sys.modules`` on entry to :cfunc:`PyImport_ExecCodeModule`.  Leaving
210-   incompletely initialized modules in ``sys.modules`` is dangerous, as imports of
211-   such modules have no way to know that the module object is an unknown (and
212-   probably damaged with respect to the module author's intents) state.
213- 
214-   This function will reload the module if it was already imported.  See
215-   :cfunc:`PyImport_ReloadModule` for the intended way to reload a module.
216- 
217-   If *name* points to a dotted name of the form ``package.module``, any package
218-   structures not already created will still not be created.
219- 
220-   .. versionchanged:: 2.4
221-      *name* is removed from ``sys.modules`` in error cases.
222- 
223- 
224-.. cfunction:: long PyImport_GetMagicNumber()
225- 
226-   Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and
227-   :file:`.pyo` files).  The magic number should be present in the first four bytes
228-   of the bytecode file, in little-endian byte order.
229- 
230- 
231-.. cfunction:: PyObject* PyImport_GetModuleDict()
232- 
233-   Return the dictionary used for the module administration (a.k.a.
234-   ``sys.modules``).  Note that this is a per-interpreter variable.
235- 
236- 
237-.. cfunction:: void _PyImport_Init()
238- 
239-   Initialize the import mechanism.  For internal use only.
240- 
241- 
242-.. cfunction:: void PyImport_Cleanup()
243- 
244-   Empty the module table.  For internal use only.
245- 
246- 
247-.. cfunction:: void _PyImport_Fini()
248- 
249-   Finalize the import mechanism.  For internal use only.
250- 
251- 
252-.. cfunction:: PyObject* _PyImport_FindExtension(char *, char *)
253- 
254-   For internal use only.
255- 
256- 
257-.. cfunction:: PyObject* _PyImport_FixupExtension(char *, char *)
258- 
259-   For internal use only.
260- 
261- 
262-.. cfunction:: int PyImport_ImportFrozenModule(char *name)
263- 
264-   Load a frozen module named *name*.  Return ``1`` for success, ``0`` if the
265-   module is not found, and ``-1`` with an exception set if the initialization
266-   failed.  To access the imported module on a successful load, use
267-   :cfunc:`PyImport_ImportModule`.  (Note the misnomer --- this function would
268-   reload the module if it was already imported.)
269- 
270- 
271-.. ctype:: struct _frozen
272- 
273-   .. index:: single: freeze utility
274- 
275-   This is the structure type definition for frozen module descriptors, as
276-   generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the
277-   Python source distribution).  Its definition, found in :file:`Include/import.h`,
278-   is::
279- 
280-      struct _frozen {
281-          char *name;
282-          unsigned char *code;
283-          int size;
284-      };
285- 
286- 
287-.. cvar:: struct _frozen* PyImport_FrozenModules
288- 
289-   This pointer is initialized to point to an array of :ctype:`struct _frozen`
290-   records, terminated by one whose members are all *NULL* or zero.  When a frozen
291-   module is imported, it is searched in this table.  Third-party code could play
292-   tricks with this to provide a dynamically created collection of frozen modules.
293- 
294- 
295-.. cfunction:: int PyImport_AppendInittab(char *name, void (*initfunc)(void))
296- 
297-   Add a single module to the existing table of built-in modules.  This is a
298-   convenience wrapper around :cfunc:`PyImport_ExtendInittab`, returning ``-1`` if
299-   the table could not be extended.  The new module can be imported by the name
300-   *name*, and uses the function *initfunc* as the initialization function called
301-   on the first attempted import.  This should be called before
302-   :cfunc:`Py_Initialize`.
303- 
304- 
305-.. ctype:: struct _inittab
306- 
307-   Structure describing a single entry in the list of built-in modules.  Each of
308-   these structures gives the name and initialization function for a module built
309-   into the interpreter.  Programs which embed Python may use an array of these
310-   structures in conjunction with :cfunc:`PyImport_ExtendInittab` to provide
311-   additional built-in modules.  The structure is defined in
312-   :file:`Include/import.h` as::
313- 
314-      struct _inittab {
315-          char *name;
316-          void (*initfunc)(void);
317-      };
318- 
319- 
320-.. cfunction:: int PyImport_ExtendInittab(struct _inittab *newtab)
321- 
322-   Add a collection of modules to the table of built-in modules.  The *newtab*
323-   array must end with a sentinel entry which contains *NULL* for the :attr:`name`
324-   field; failure to provide the sentinel value can result in a memory fault.
325-   Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to
326-   extend the internal table.  In the event of failure, no modules are added to the
327-   internal table.  This should be called before :cfunc:`Py_Initialize`.
328- 
329- 
330-.. _marshalling-utils:
331- 
332-Data marshalling support
333-========================
334- 
335-These routines allow C code to work with serialized objects using the same data
336-format as the :mod:`marshal` module.  There are functions to write data into the
337-serialization format, and additional functions that can be used to read the data
338-back.  Files used to store marshalled data must be opened in binary mode.
339- 
340-Numeric values are stored with the least significant byte first.
341- 
342-The module supports two versions of the data format: version 0 is the historical
343-version, version 1 (new in Python 2.4) shares interned strings in the file, and
344-upon unmarshalling. *Py_MARSHAL_VERSION* indicates the current file format
345-(currently 1).
346- 
347- 
348-.. cfunction:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
349- 
350-   Marshal a :ctype:`long` integer, *value*, to *file*.  This will only write the
351-   least-significant 32 bits of *value*; regardless of the size of the native
352-   :ctype:`long` type.
353- 
354-   .. versionchanged:: 2.4
355-      *version* indicates the file format.
356- 
357- 
358-.. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
359- 
360-   Marshal a Python object, *value*, to *file*.
361- 
362-   .. versionchanged:: 2.4
363-      *version* indicates the file format.
364- 
365- 
366-.. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version)
367- 
368-   Return a string object containing the marshalled representation of *value*.
369- 
370-   .. versionchanged:: 2.4
371-      *version* indicates the file format.
372- 
373-The following functions allow marshalled values to be read back in.
374- 
375-XXX What about error detection?  It appears that reading past the end of the
376-file will always result in a negative numeric value (where that's relevant), but
377-it's not clear that negative values won't be handled properly when there's no
378-error.  What's the right way to tell? Should only non-negative values be written
379-using these routines?
380- 
381- 
382-.. cfunction:: long PyMarshal_ReadLongFromFile(FILE *file)
383- 
384-   Return a C :ctype:`long` from the data stream in a :ctype:`FILE\*` opened for
385-   reading.  Only a 32-bit value can be read in using this function, regardless of
386-   the native size of :ctype:`long`.
387- 
388- 
389-.. cfunction:: int PyMarshal_ReadShortFromFile(FILE *file)
390- 
391-   Return a C :ctype:`short` from the data stream in a :ctype:`FILE\*` opened for
392-   reading.  Only a 16-bit value can be read in using this function, regardless of
393-   the native size of :ctype:`short`.
394- 
395- 
396-.. cfunction:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file)
397- 
398-   Return a Python object from the data stream in a :ctype:`FILE\*` opened for
399-   reading.  On error, sets the appropriate exception (:exc:`EOFError` or
400-   :exc:`TypeError`) and returns *NULL*.
401- 
402- 
403-.. cfunction:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file)
404- 
405-   Return a Python object from the data stream in a :ctype:`FILE\*` opened for
406-   reading.  Unlike :cfunc:`PyMarshal_ReadObjectFromFile`, this function assumes
407-   that no further objects will be read from the file, allowing it to aggressively
408-   load file data into memory so that the de-serialization can operate from data in
409-   memory rather than reading a byte at a time from the file.  Only use these
410-   variant if you are certain that you won't be reading anything else from the
411-   file.  On error, sets the appropriate exception (:exc:`EOFError` or
412-   :exc:`TypeError`) and returns *NULL*.
413- 
414- 
415-.. cfunction:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len)
416- 
417-   Return a Python object from the data stream in a character buffer containing
418-   *len* bytes pointed to by *string*.  On error, sets the appropriate exception
419-   (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*.
420- 
421- 
422-.. _arg-parsing:
423- 
424-Parsing arguments and building values
425-=====================================
426- 
427-These functions are useful when creating your own extensions functions and
428-methods.  Additional information and examples are available in Extending and
429-Embedding the Python Interpreter (XXX reference: ../ext/ext.html).
430- 
431-The first three of these functions described, :cfunc:`PyArg_ParseTuple`,
432-:cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use *format
433-strings* which are used to tell the function about the expected arguments.  The
434-format strings use the same syntax for each of these functions.
435- 
436-A format string consists of zero or more "format units."  A format unit
437-describes one Python object; it is usually a single character or a parenthesized
438-sequence of format units.  With a few exceptions, a format unit that is not a
439-parenthesized sequence normally corresponds to a single address argument to
440-these functions.  In the following description, the quoted form is the format
441-unit; the entry in (round) parentheses is the Python object type that matches
442-the format unit; and the entry in [square] brackets is the type of the C
443-variable(s) whose address should be passed.
444- 
445-``s`` (string or Unicode object) [const char \*]
446-   Convert a Python string or Unicode object to a C pointer to a character string.
447-   You must not provide storage for the string itself; a pointer to an existing
448-   string is stored into the character pointer variable whose address you pass.
449-   The C string is NUL-terminated.  The Python string must not contain embedded NUL
450-   bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are
451-   converted to C strings using the default encoding.  If this conversion fails, a
452-   :exc:`UnicodeError` is raised.
453- 
454-``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int]
455-   This variant on ``s`` stores into two C variables, the first one a pointer to a
456-   character string, the second one its length.  In this case the Python string may
457-   contain embedded null bytes.  Unicode objects pass back a pointer to the default
458-   encoded string version of the object if such a conversion is possible.  All
459-   other read-buffer compatible objects pass back a reference to the raw internal
460-   data representation.
461- 
462-``z`` (string or ``None``) [const char \*]
463-   Like ``s``, but the Python object may also be ``None``, in which case the C
464-   pointer is set to *NULL*.
465- 
466-``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int]
467-   This is to ``s#`` as ``z`` is to ``s``.
468- 
469-``u`` (Unicode object) [Py_UNICODE \*]
470-   Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of
471-   16-bit Unicode (UTF-16) data.  As with ``s``, there is no need to provide
472-   storage for the Unicode data buffer; a pointer to the existing Unicode data is
473-   stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass.
474- 
475-``u#`` (Unicode object) [Py_UNICODE \*, int]
476-   This variant on ``u`` stores into two C variables, the first one a pointer to a
477-   Unicode data buffer, the second one its length. Non-Unicode objects are handled
478-   by interpreting their read-buffer pointer as pointer to a :ctype:`Py_UNICODE`
479-   array.
480- 
481-``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
482-   This variant on ``s`` is used for encoding Unicode and objects convertible to
483-   Unicode into a character buffer. It only works for encoded data without embedded
484-   NUL bytes.
485- 
486-   This format requires two arguments.  The first is only used as input, and must
487-   be a :ctype:`const char\*` which points to the name of an encoding as a NUL-
488-   terminated string, or *NULL*, in which case the default encoding is used.  An
489-   exception is raised if the named encoding is not known to Python.  The second
490-   argument must be a :ctype:`char\*\*`; the value of the pointer it references
491-   will be set to a buffer with the contents of the argument text.  The text will
492-   be encoded in the encoding specified by the first argument.
493- 
494-   :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the
495-   encoded data into this buffer and adjust *\*buffer* to reference the newly
496-   allocated storage.  The caller is responsible for calling :cfunc:`PyMem_Free` to
497-   free the allocated buffer after use.
498- 
499-``et`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
500-   Same as ``es`` except that 8-bit string objects are passed through without
501-   recoding them.  Instead, the implementation assumes that the string object uses
502-   the encoding passed in as parameter.
503- 
504-``es#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
505-   This variant on ``s#`` is used for encoding Unicode and objects convertible to
506-   Unicode into a character buffer.  Unlike the ``es`` format, this variant allows
507-   input data which contains NUL characters.
508- 
509-   It requires three arguments.  The first is only used as input, and must be a
510-   :ctype:`const char\*` which points to the name of an encoding as a NUL-
511-   terminated string, or *NULL*, in which case the default encoding is used.  An
512-   exception is raised if the named encoding is not known to Python.  The second
513-   argument must be a :ctype:`char\*\*`; the value of the pointer it references
514-   will be set to a buffer with the contents of the argument text.  The text will
515-   be encoded in the encoding specified by the first argument.  The third argument
516-   must be a pointer to an integer; the referenced integer will be set to the
517-   number of bytes in the output buffer.
518- 
519-   There are two modes of operation:
520- 
521-   If *\*buffer* points a *NULL* pointer, the function will allocate a buffer of
522-   the needed size, copy the encoded data into this buffer and set *\*buffer* to
523-   reference the newly allocated storage.  The caller is responsible for calling
524-   :cfunc:`PyMem_Free` to free the allocated buffer after usage.
525- 
526-   If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer),
527-   :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the
528-   initial value of *\*buffer_length* as the buffer size.  It will then copy the
529-   encoded data into the buffer and NUL-terminate it.  If the buffer is not large
530-   enough, a :exc:`ValueError` will be set.
531- 
532-   In both cases, *\*buffer_length* is set to the length of the encoded data
533-   without the trailing NUL byte.
534- 
535-``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
536-   Same as ``es#`` except that string objects are passed through without recoding
537-   them. Instead, the implementation assumes that the string object uses the
538-   encoding passed in as parameter.
539- 
540-``b`` (integer) [char]
541-   Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
542- 
543-``B`` (integer) [unsigned char]
544-   Convert a Python integer to a tiny int without overflow checking, stored in a C
545-   :ctype:`unsigned char`.
546- 
547-   .. versionadded:: 2.3
548- 
549-``h`` (integer) [short int]
550-   Convert a Python integer to a C :ctype:`short int`.
551- 
552-``H`` (integer) [unsigned short int]
553-   Convert a Python integer to a C :ctype:`unsigned short int`, without overflow
554-   checking.
555- 
556-   .. versionadded:: 2.3
557- 
558-``i`` (integer) [int]
559-   Convert a Python integer to a plain C :ctype:`int`.
560- 
561-``I`` (integer) [unsigned int]
562-   Convert a Python integer to a C :ctype:`unsigned int`, without overflow
563-   checking.
564- 
565-   .. versionadded:: 2.3
566- 
567-``l`` (integer) [long int]
568-   Convert a Python integer to a C :ctype:`long int`.
569- 
570-``k`` (integer) [unsigned long]
571-   Convert a Python integer or long integer to a C :ctype:`unsigned long` without
572-   overflow checking.
573- 
574-   .. versionadded:: 2.3
575- 
576-``L`` (integer) [PY_LONG_LONG]
577-   Convert a Python integer to a C :ctype:`long long`.  This format is only
578-   available on platforms that support :ctype:`long long` (or :ctype:`_int64` on
579-   Windows).
580- 
581-``K`` (integer) [unsigned PY_LONG_LONG]
582-   Convert a Python integer or long integer to a C :ctype:`unsigned long long`
583-   without overflow checking.  This format is only available on platforms that
584-   support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows).
585- 
586-   .. versionadded:: 2.3
587- 
588-``n`` (integer) [Py_ssize_t]
589-   Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`.
590- 
591-   .. versionadded:: 2.5
592- 
593-``c`` (string of length 1) [char]
594-   Convert a Python character, represented as a string of length 1, to a C
595-   :ctype:`char`.
596- 
597-``f`` (float) [float]
598-   Convert a Python floating point number to a C :ctype:`float`.
599- 
600-``d`` (float) [double]
601-   Convert a Python floating point number to a C :ctype:`double`.
602- 
603-``D`` (complex) [Py_complex]
604-   Convert a Python complex number to a C :ctype:`Py_complex` structure.
605- 
606-``O`` (object) [PyObject \*]
607-   Store a Python object (without any conversion) in a C object pointer.  The C
608-   program thus receives the actual object that was passed.  The object's reference
609-   count is not increased.  The pointer stored is not *NULL*.
610- 
611-``O!`` (object) [*typeobject*, PyObject \*]
612-   Store a Python object in a C object pointer.  This is similar to ``O``, but
613-   takes two C arguments: the first is the address of a Python type object, the
614-   second is the address of the C variable (of type :ctype:`PyObject\*`) into which
615-   the object pointer is stored.  If the Python object does not have the required
616-   type, :exc:`TypeError` is raised.
617- 
618-``O&`` (object) [*converter*, *anything*]
619-   Convert a Python object to a C variable through a *converter* function.  This
620-   takes two arguments: the first is a function, the second is the address of a C
621-   variable (of arbitrary type), converted to :ctype:`void \*`.  The *converter*
622-   function in turn is called as follows:
623- 
624-   *status*``=``*converter*``(``*object*, *address*``);``
625- 
626-   where *object* is the Python object to be converted and *address* is the
627-   :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function.
628-   The returned *status* should be ``1`` for a successful conversion and ``0`` if
629-   the conversion has failed.  When the conversion fails, the *converter* function
630-   should raise an exception.
631- 
632-``S`` (string) [PyStringObject \*]
633-   Like ``O`` but requires that the Python object is a string object.  Raises
634-   :exc:`TypeError` if the object is not a string object.  The C variable may also
635-   be declared as :ctype:`PyObject\*`.
636- 
637-``U`` (Unicode string) [PyUnicodeObject \*]
638-   Like ``O`` but requires that the Python object is a Unicode object.  Raises
639-   :exc:`TypeError` if the object is not a Unicode object.  The C variable may also
640-   be declared as :ctype:`PyObject\*`.
641- 
642-``t#`` (read-only character buffer) [char \*, int]
643-   Like ``s#``, but accepts any object which implements the read-only buffer
644-   interface.  The :ctype:`char\*` variable is set to point to the first byte of
645-   the buffer, and the :ctype:`int` is set to the length of the buffer.  Only
646-   single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
647-   others.
648- 
649-``w`` (read-write character buffer) [char \*]
650-   Similar to ``s``, but accepts any object which implements the read-write buffer
651-   interface.  The caller must determine the length of the buffer by other means,
652-   or use ``w#`` instead.  Only single-segment buffer objects are accepted;
653-   :exc:`TypeError` is raised for all others.
654- 
655-``w#`` (read-write character buffer) [char \*, int]
656-   Like ``s#``, but accepts any object which implements the read-write buffer
657-   interface.  The :ctype:`char \*` variable is set to point to the first byte of
658-   the buffer, and the :ctype:`int` is set to the length of the buffer.  Only
659-   single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
660-   others.
661- 
662-``(items)`` (tuple) [*matching-items*]
663-   The object must be a Python sequence whose length is the number of format units
664-   in *items*.  The C arguments must correspond to the individual format units in
665-   *items*.  Format units for sequences may be nested.
666- 
667-   .. note::
668- 
669-      Prior to Python version 1.5.2, this format specifier only accepted a tuple
670-      containing the individual parameters, not an arbitrary sequence.  Code which
671-      previously caused :exc:`TypeError` to be raised here may now proceed without an
672-      exception.  This is not expected to be a problem for existing code.
673- 
674-It is possible to pass Python long integers where integers are requested;
675-however no proper range checking is done --- the most significant bits are
676-silently truncated when the receiving field is too small to receive the value
677-(actually, the semantics are inherited from downcasts in C --- your mileage may
678-vary).
679- 
680-A few other characters have a meaning in a format string.  These may not occur
681-inside nested parentheses.  They are:
682- 
683-``|``
684-   Indicates that the remaining arguments in the Python argument list are optional.
685-   The C variables corresponding to optional arguments should be initialized to
686-   their default value --- when an optional argument is not specified,
687-   :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C
688-   variable(s).
689- 
690-``:``
691-   The list of format units ends here; the string after the colon is used as the
692-   function name in error messages (the "associated value" of the exception that
693-   :cfunc:`PyArg_ParseTuple` raises).
694- 
695-``;``
696-   The list of format units ends here; the string after the semicolon is used as
697-   the error message *instead* of the default error message.  Clearly, ``:`` and
698-   ``;`` mutually exclude each other.
699- 
700-Note that any Python object references which are provided to the caller are
701-*borrowed* references; do not decrement their reference count!
702- 
703-Additional arguments passed to these functions must be addresses of variables
704-whose type is determined by the format string; these are used to store values
705-from the input tuple.  There are a few cases, as described in the list of format
706-units above, where these parameters are used as input values; they should match
707-what is specified for the corresponding format unit in that case.
708- 
709-For the conversion to succeed, the *arg* object must match the format and the
710-format must be exhausted.  On success, the :cfunc:`PyArg_Parse\*` functions
711-return true, otherwise they return false and raise an appropriate exception.
712- 
713- 
714-.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
715- 
716-   Parse the parameters of a function that takes only positional parameters into
717-   local variables.  Returns true on success; on failure, it returns false and
718-   raises the appropriate exception.
719- 
720- 
721-.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
722- 
723-   Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather
724-   than a variable number of arguments.
725- 
726- 
727-.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
728- 
729-   Parse the parameters of a function that takes both positional and keyword
730-   parameters into local variables.  Returns true on success; on failure, it
731-   returns false and raises the appropriate exception.
732- 
733- 
734-.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
735- 
736-   Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a
737-   va_list rather than a variable number of arguments.
738- 
739- 
740-.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...)
741- 
742-   Function used to deconstruct the argument lists of "old-style" functions ---
743-   these are functions which use the :const:`METH_OLDARGS` parameter parsing
744-   method.  This is not recommended for use in parameter parsing in new code, and
745-   most code in the standard interpreter has been modified to no longer use this
746-   for that purpose.  It does remain a convenient way to decompose other tuples,
747-   however, and may continue to be used for that purpose.
748- 
749- 
750-.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
751- 
752-   A simpler form of parameter retrieval which does not use a format string to
753-   specify the types of the arguments.  Functions which use this method to retrieve
754-   their parameters should be declared as :const:`METH_VARARGS` in function or
755-   method tables.  The tuple containing the actual parameters should be passed as
756-   *args*; it must actually be a tuple.  The length of the tuple must be at least
757-   *min* and no more than *max*; *min* and *max* may be equal.  Additional
758-   arguments must be passed to the function, each of which should be a pointer to a
759-   :ctype:`PyObject\*` variable; these will be filled in with the values from
760-   *args*; they will contain borrowed references.  The variables which correspond
761-   to optional parameters not given by *args* will not be filled in; these should
762-   be initialized by the caller. This function returns true on success and false if
763-   *args* is not a tuple or contains the wrong number of elements; an exception
764-   will be set if there was a failure.
765- 
766-   This is an example of the use of this function, taken from the sources for the
767-   :mod:`_weakref` helper module for weak references::
768- 
769-      static PyObject *
770-      weakref_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- 
782-   The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to
783-   this call to :cfunc:`PyArg_ParseTuple`::
784- 
785-      PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
786- 
787-   .. versionadded:: 2.2
788- 
789- 
790-.. cfunction:: PyObject* Py_BuildValue(const char *format, ...)
791- 
792-   Create a new value based on a format string similar to those accepted by the
793-   :cfunc:`PyArg_Parse\*` family of functions and a sequence of values.  Returns
794-   the value or *NULL* in the case of an error; an exception will be raised if
795-   *NULL* is returned.
796- 
797-   :cfunc:`Py_BuildValue` does not always build a tuple.  It builds a tuple only if
798-   its format string contains two or more format units.  If the format string is
799-   empty, it returns ``None``; if it contains exactly one format unit, it returns
800-   whatever object is described by that format unit.  To force it to return a tuple
801-   of size 0 or one, parenthesize the format string.
802- 
803-   When memory buffers are passed as parameters to supply data to build objects, as
804-   for the ``s`` and ``s#`` formats, the required data is copied.  Buffers provided
805-   by the caller are never referenced by the objects created by
806-   :cfunc:`Py_BuildValue`.  In other words, if your code invokes :cfunc:`malloc`
807-   and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is
808-   responsible for calling :cfunc:`free` for that memory once
809-   :cfunc:`Py_BuildValue` returns.
810- 
811-   In the following description, the quoted form is the format unit; the entry in
812-   (round) parentheses is the Python object type that the format unit will return;
813-   and the entry in [square] brackets is the type of the C value(s) to be passed.
814- 
815-   The characters space, tab, colon and comma are ignored in format strings (but
816-   not within format units such as ``s#``).  This can be used to make long format
817-   strings a tad more readable.
818- 
819-   ``s`` (string) [char \*]
820-      Convert a null-terminated C string to a Python object.  If the C string pointer
821-      is *NULL*, ``None`` is used.
822- 
823-   ``s#`` (string) [char \*, int]
824-      Convert a C string and its length to a Python object.  If the C string pointer
825-      is *NULL*, the length is ignored and ``None`` is returned.
826- 
827-   ``z`` (string or ``None``) [char \*]
828-      Same as ``s``.
829- 
830-   ``z#`` (string or ``None``) [char \*, int]
831-      Same as ``s#``.
832- 
833-   ``u`` (Unicode string) [Py_UNICODE \*]
834-      Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python
835-      Unicode object.  If the Unicode buffer pointer is *NULL*, ``None`` is returned.
836- 
837-   ``u#`` (Unicode string) [Py_UNICODE \*, int]
838-      Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python
839-      Unicode object.   If the Unicode buffer pointer is *NULL*, the length is ignored
840-      and ``None`` is returned.
841- 
842-   ``i`` (integer) [int]
843-      Convert a plain C :ctype:`int` to a Python integer object.
844- 
845-   ``b`` (integer) [char]
846-      Convert a plain C :ctype:`char` to a Python integer object.
847- 
848-   ``h`` (integer) [short int]
849-      Convert a plain C :ctype:`short int` to a Python integer object.
850- 
851-   ``l`` (integer) [long int]
852-      Convert a C :ctype:`long int` to a Python integer object.
853- 
854-   ``B`` (integer) [unsigned char]
855-      Convert a C :ctype:`unsigned char` to a Python integer object.
856- 
857-   ``H`` (integer) [unsigned short int]
858-      Convert a C :ctype:`unsigned short int` to a Python integer object.
859- 
860-   ``I`` (integer/long) [unsigned int]
861-      Convert a C :ctype:`unsigned int` to a Python integer object or a Python long
862-      integer object, if it is larger than ``sys.maxint``.
863- 
864-   ``k`` (integer/long) [unsigned long]
865-      Convert a C :ctype:`unsigned long` to a Python integer object or a Python long
866-      integer object, if it is larger than ``sys.maxint``.
867- 
868-   ``L`` (long) [PY_LONG_LONG]
869-      Convert a C :ctype:`long long` to a Python long integer object. Only available
870-      on platforms that support :ctype:`long long`.
871- 
872-   ``K`` (long) [unsigned PY_LONG_LONG]
873-      Convert a C :ctype:`unsigned long long` to a Python long integer object. Only
874-      available on platforms that support :ctype:`unsigned long long`.
875- 
876-   ``n`` (int) [Py_ssize_t]
877-      Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer.
878- 
879-      .. versionadded:: 2.5
880- 
881-   ``c`` (string of length 1) [char]
882-      Convert a C :ctype:`int` representing a character to a Python string of length
883-      1.
884- 
885-   ``d`` (float) [double]
886-      Convert a C :ctype:`double` to a Python floating point number.
887- 
888-   ``f`` (float) [float]
889-      Same as ``d``.
890- 
891-   ``D`` (complex) [Py_complex \*]
892-      Convert a C :ctype:`Py_complex` structure to a Python complex number.
893- 
894-   ``O`` (object) [PyObject \*]
895-      Pass a Python object untouched (except for its reference count, which is
896-      incremented by one).  If the object passed in is a *NULL* pointer, it is assumed
897-      that this was caused because the call producing the argument found an error and
898-      set an exception. Therefore, :cfunc:`Py_BuildValue` will return *NULL* but won't
899-      raise an exception.  If no exception has been raised yet, :exc:`SystemError` is
900-      set.
901- 
902-   ``S`` (object) [PyObject \*]
903-      Same as ``O``.
904- 
905-   ``N`` (object) [PyObject \*]
906-      Same as ``O``, except it doesn't increment the reference count on the object.
907-      Useful when the object is created by a call to an object constructor in the
908-      argument list.
909- 
910-   ``O&`` (object) [*converter*, *anything*]
911-      Convert *anything* to a Python object through a *converter* function.  The
912-      function is called with *anything* (which should be compatible with :ctype:`void
913-      \*`) as its argument and should return a "new" Python object, or *NULL* if an
914-      error occurred.
915- 
916-   ``(items)`` (tuple) [*matching-items*]
917-      Convert a sequence of C values to a Python tuple with the same number of items.
918- 
919-   ``[items]`` (list) [*matching-items*]
920-      Convert a sequence of C values to a Python list with the same number of items.
921- 
922-   ``{items}`` (dictionary) [*matching-items*]
923-      Convert a sequence of C values to a Python dictionary.  Each pair of consecutive
924-      C values adds one item to the dictionary, serving as key and value,
925-      respectively.
926- 
927-   If there is an error in the format string, the :exc:`SystemError` exception is
928-   set and *NULL* returned.
929- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op