\chapter{Utilities \label{utilities}} The functions in this chapter perform various utility tasks, rangingfrom helping C code be more portable across platforms, using Pythonmodules from C, and parsing function arguments and constructing Pythonvalues from C values. \section{Operating System Utilities \label{os}} \begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, const char *filename} Return true (nonzero) if the standard I/O file \var{fp} with name \var{filename} is deemed interactive. This is the case for files for which \samp{isatty(fileno(\var{fp}))} is true. If the global flag \cdata{Py_InteractiveFlag} is true, this function also returns true if the \var{filename} pointer is \NULL{} or if the name is equal to one of the strings \code{'<stdin>'} or \code{'???'}.\end{cfuncdesc} \begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename} Return the time of last modification of the file \var{filename}. The result is encoded in the same way as the timestamp returned by the standard C library function \cfunction{time()}.\end{cfuncdesc} \begin{cfuncdesc}{void}{PyOS_AfterFork}{} Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. If a new executable is loaded into the new process, this function does not need to be called.\end{cfuncdesc} \begin{cfuncdesc}{int}{PyOS_CheckStack}{} Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when \constant{USE_STACKCHECK} is defined (currently on Windows using the Microsoft Visual \Cpp{} compiler). \constant{USE_STACKCHECK} will be defined automatically; you should never change the definition in your own code.\end{cfuncdesc} \begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i} Return the current signal handler for signal \var{i}. This is a thin wrapper around either \cfunction{sigaction()} or \cfunction{signal()}. Do not call those functions directly! \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.\end{cfuncdesc} \begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h} Set the signal handler for signal \var{i} to be \var{h}; return the old signal handler. This is a thin wrapper around either \cfunction{sigaction()} or \cfunction{signal()}. Do not call those functions directly! \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.\end{cfuncdesc} \section{Process Control \label{processControl}} \begin{cfuncdesc}{void}{Py_FatalError}{const char *message} Print a fatal error message and kill the process. No cleanup is performed. This function should only be invoked when a condition is detected that would make it dangerous to continue using the Python interpreter; e.g., when the object administration appears to be corrupted. On \UNIX, the standard C library function \cfunction{abort()}\ttindex{abort()} is called which will attempt to produce a \file{core} file.\end{cfuncdesc} \begin{cfuncdesc}{void}{Py_Exit}{int status} Exit the current process. This calls \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and then calls the standard C library function \code{exit(\var{status})}\ttindex{exit()}.\end{cfuncdesc} \begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()} Register a cleanup function to be called by \cfunction{Py_Finalize()}\ttindex{Py_Finalize()}. The cleanup function will be called with no arguments and should return no value. At most 32 \index{cleanup functions}cleanup functions can be registered. When the registration is successful, \cfunction{Py_AtExit()} returns \code{0}; on failure, it returns \code{-1}. The cleanup function registered last is called first. Each cleanup function will be called at most once. Since Python's internal finalization will have completed before the cleanup function, no Python APIs should be called by \var{func}.\end{cfuncdesc} \section{Importing Modules \label{importing}} \begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{const char *name} This is a simplified interface to \cfunction{PyImport_ImportModuleEx()} below, leaving the \var{globals} and \var{locals} arguments set to \NULL. When the \var{name} argument contains a dot (when it specifies a submodule of a package), the \var{fromlist} argument is set to the list \code{['*']} so that the return value is the named module rather than the top-level package containing it as would otherwise be the case. (Unfortunately, this has an additional side effect when \var{name} in fact specifies a subpackage instead of a submodule: the submodules specified in the package's \code{__all__} variable are \index{package variable!\code{__all__}} \withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a new reference to the imported module, or \NULL{} with an exception set on failure. Before Python 2.4, the module may still be created in the failure case --- examine \code{sys.modules} to find out. Starting with Python 2.4, a failing import of a module no longer leaves the module in \code{sys.modules}. \versionchanged[failing imports remove incomplete module objects]{2.4} \withsubitem{(in module sys)}{\ttindex{modules}}\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist} Import a module. This is best described by referring to the built-in Python function \function{__import__()}\bifuncindex{__import__}, as the standard \function{__import__()} function calls this function directly. The return value is a new reference to the imported module or top-level package, or \NULL{} with an exception set on failure (before Python 2.4, the module may still be created in this case). Like for \function{__import__()}, the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty \var{fromlist} was given. \versionchanged[failing imports remove incomplete module objects]{2.4}\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name} This is a higher-level interface that calls the current ``import hook function''. It invokes the \function{__import__()} function from the \code{__builtins__} of the current globals. This means that the import is done using whatever import hooks are installed in the current environment, e.g. by \module{rexec}\refstmodindex{rexec} or \module{ihooks}\refstmodindex{ihooks}.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m} Reload a module. This is best described by referring to the built-in Python function \function{reload()}\bifuncindex{reload}, as the standard \function{reload()} function calls this function directly. Return a new reference to the reloaded module, or \NULL{} with an exception set on failure (the module still exists in this case).\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{const char *name} Return the module object corresponding to a module name. The \var{name} argument may be of the form \code{package.module}. First check the modules dictionary if there's one there, and if not, create a new one and insert it in the modules dictionary. Return \NULL{} with an exception set on failure. \note{This function does not load or import the module; if the module wasn't already loaded, you will get an empty module object. Use \cfunction{PyImport_ImportModule()} or one of its variants to import a module. Package structures implied by a dotted name for \var{name} are not created if not already present.}\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co} Given a module name (possibly of the form \code{package.module}) and a code object read from a Python bytecode file or obtained from the built-in function \function{compile()}\bifuncindex{compile}, load the module. Return a new reference to the module object, or \NULL{} with an exception set if an error occurred. Before Python 2.4, the module could still be created in error cases. Starting with Python 2.4, \var{name} is removed from \code{sys.modules} in error cases, and even if \var{name} was already in \code{sys.modules} on entry to \cfunction{PyImport_ExecCodeModule()}. Leaving incompletely initialized modules in \code{sys.modules} is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author's intents) state. This function will reload the module if it was already imported. See \cfunction{PyImport_ReloadModule()} for the intended way to reload a module. If \var{name} points to a dotted name of the form \code{package.module}, any package structures not already created will still not be created. \versionchanged[\var{name} is removed from \code{sys.modules} in error cases]{2.4} \end{cfuncdesc} \begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{} Return the magic number for Python bytecode files (a.k.a. \file{.pyc} and \file{.pyo} files). The magic number should be present in the first four bytes of the bytecode file, in little-endian byte order.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{} Return the dictionary used for the module administration (a.k.a.\ \code{sys.modules}). Note that this is a per-interpreter variable.\end{cfuncdesc} \begin{cfuncdesc}{void}{_PyImport_Init}{} Initialize the import mechanism. For internal use only.\end{cfuncdesc} \begin{cfuncdesc}{void}{PyImport_Cleanup}{} Empty the module table. For internal use only.\end{cfuncdesc} \begin{cfuncdesc}{void}{_PyImport_Fini}{} Finalize the import mechanism. For internal use only.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *} For internal use only.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *} For internal use only.\end{cfuncdesc} \begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name} Load a frozen module named \var{name}. Return \code{1} for success, \code{0} if the module is not found, and \code{-1} with an exception set if the initialization failed. To access the imported module on a successful load, use \cfunction{PyImport_ImportModule()}. (Note the misnomer --- this function would reload the module if it was already imported.)\end{cfuncdesc} \begin{ctypedesc}[_frozen]{struct _frozen} This is the structure type definition for frozen module descriptors, as generated by the \program{freeze}\index{freeze utility} utility (see \file{Tools/freeze/} in the Python source distribution). Its definition, found in \file{Include/import.h}, is: \begin{verbatim}struct _frozen { char *name; unsigned char *code; int size;};\end{verbatim}\end{ctypedesc} \begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules} This pointer is initialized to point to an array of \ctype{struct _frozen} records, terminated by one whose members are all \NULL{} or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.\end{cvardesc} \begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name, void (*initfunc)(void)} Add a single module to the existing table of built-in modules. This is a convenience wrapper around \cfunction{PyImport_ExtendInittab()}, returning \code{-1} if the table could not be extended. The new module can be imported by the name \var{name}, and uses the function \var{initfunc} as the initialization function called on the first attempted import. This should be called before \cfunction{Py_Initialize()}.\end{cfuncdesc} \begin{ctypedesc}[_inittab]{struct _inittab} Structure describing a single entry in the list of built-in modules. Each of these structures gives the name and initialization function for a module built into the interpreter. Programs which embed Python may use an array of these structures in conjunction with \cfunction{PyImport_ExtendInittab()} to provide additional built-in modules. The structure is defined in \file{Include/import.h} as: \begin{verbatim}struct _inittab { char *name; void (*initfunc)(void);};\end{verbatim}\end{ctypedesc} \begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab} Add a collection of modules to the table of built-in modules. The \var{newtab} array must end with a sentinel entry which contains \NULL{} for the \member{name} field; failure to provide the sentinel value can result in a memory fault. Returns \code{0} on success or \code{-1} if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the internal table. This should be called before \cfunction{Py_Initialize()}.\end{cfuncdesc} \section{Data marshalling support \label{marshalling-utils}} These routines allow C code to work with serialized objects using thesame data format as the \module{marshal} module. There are functionsto write data into the serialization format, and additional functionsthat can be used to read the data back. Files used to store marshalleddata must be opened in binary mode. Numeric values are stored with the least significant byte first. The module supports two versions of the data format: version 0 is thehistorical version, version 1 (new in Python 2.4) shares internedstrings in the file, and upon unmarshalling. \var{Py_MARSHAL_VERSION}indicates the current file format (currently 1). \begin{cfuncdesc}{void}{PyMarshal_WriteLongToFile}{long value, FILE *file, int version} Marshal a \ctype{long} integer, \var{value}, to \var{file}. This will only write the least-significant 32 bits of \var{value}; regardless of the size of the native \ctype{long} type. \versionchanged[\var{version} indicates the file format]{2.4}\end{cfuncdesc} \begin{cfuncdesc}{void}{PyMarshal_WriteObjectToFile}{PyObject *value, FILE *file, int version} Marshal a Python object, \var{value}, to \var{file}. \versionchanged[\var{version} indicates the file format]{2.4}\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_WriteObjectToString}{PyObject *value, int version} Return a string object containing the marshalled representation of \var{value}. \versionchanged[\var{version} indicates the file format]{2.4}\end{cfuncdesc} The following functions allow marshalled values to be read back in. XXX What about error detection? It appears that reading past the endof the file will always result in a negative numeric value (wherethat's relevant), but it's not clear that negative values won't behandled properly when there's no error. What's the right way to tell?Should only non-negative values be written using these routines? \begin{cfuncdesc}{long}{PyMarshal_ReadLongFromFile}{FILE *file} Return a C \ctype{long} from the data stream in a \ctype{FILE*} opened for reading. Only a 32-bit value can be read in using this function, regardless of the native size of \ctype{long}.\end{cfuncdesc} \begin{cfuncdesc}{int}{PyMarshal_ReadShortFromFile}{FILE *file} Return a C \ctype{short} from the data stream in a \ctype{FILE*} opened for reading. Only a 16-bit value can be read in using this function, regardless of the native size of \ctype{short}.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromFile}{FILE *file} Return a Python object from the data stream in a \ctype{FILE*} opened for reading. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadLastObjectFromFile}{FILE *file} Return a Python object from the data stream in a \ctype{FILE*} opened for reading. Unlike \cfunction{PyMarshal_ReadObjectFromFile()}, this function assumes that no further objects will be read from the file, allowing it to aggressively load file data into memory so that the de-serialization can operate from data in memory rather than reading a byte at a time from the file. Only use these variant if you are certain that you won't be reading anything else from the file. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL.\end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromString}{char *string, Py_ssize_t len} Return a Python object from the data stream in a character buffer containing \var{len} bytes pointed to by \var{string}. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL.\end{cfuncdesc} \section{Parsing arguments and building values \label{arg-parsing}} These functions are useful when creating your own extensions functionsand methods. Additional information and examples are available in\citetitle[../ext/ext.html]{Extending and Embedding the PythonInterpreter}. The first three of these functions described,\cfunction{PyArg_ParseTuple()},\cfunction{PyArg_ParseTupleAndKeywords()}, and\cfunction{PyArg_Parse()}, all use \emph{format strings} which areused to tell the function about the expected arguments. The formatstrings use the same syntax for each of these functions. A format string consists of zero or more ``format units.'' A formatunit describes one Python object; it is usually a single character ora parenthesized sequence of format units. With a few exceptions, aformat unit that is not a parenthesized sequence normally correspondsto a single address argument to these functions. In the followingdescription, the quoted form is the format unit; the entry in (round)parentheses is the Python object type that matches the format unit;and the entry in [square] brackets is the type of the C variable(s)whose address should be passed. \begin{description} \item[\samp{s} (string or Unicode object) {[const char *]}] Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded NUL bytes; if it does, a \exception{TypeError} exception is raised. Unicode objects are converted to C strings using the default encoding. If this conversion fails, a \exception{UnicodeError} is raised. \item[\samp{s\#} (string, Unicode or any read buffer compatible object) {[const char *, int]}] This variant on \samp{s} stores into two C variables, the first one a pointer to a character string, the second one its length. In this case the Python string may contain embedded null bytes. Unicode objects pass back a pointer to the default encoded string version of the object if such a conversion is possible. All other read-buffer compatible objects pass back a reference to the raw internal data representation. \item[\samp{z} (string or \code{None}) {[const char *]}] Like \samp{s}, but the Python object may also be \code{None}, in which case the C pointer is set to \NULL. \item[\samp{z\#} (string or \code{None} or any read buffer compatible object) {[const char *, int]}] This is to \samp{s\#} as \samp{z} is to \samp{s}. \item[\samp{u} (Unicode object) {[Py_UNICODE *]}] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need to provide storage for the Unicode data buffer; a pointer to the existing Unicode data is stored into the \ctype{Py_UNICODE} pointer variable whose address you pass. \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}] This variant on \samp{u} stores into two C variables, the first one a pointer to a Unicode data buffer, the second one its length. Non-Unicode objects are handled by interpreting their read-buffer pointer as pointer to a \ctype{Py_UNICODE} array. \item[\samp{es} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer]}] This variant on \samp{s} is used for encoding Unicode and objects convertible to Unicode into a character buffer. It only works for encoded data without embedded NUL bytes. This format requires two arguments. The first is only used as input, and must be a \ctype{const char*} which points to the name of an encoding as a NUL-terminated string, or \NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a \ctype{char**}; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust \var{*buffer} to reference the newly allocated storage. The caller is responsible for calling \cfunction{PyMem_Free()} to free the allocated buffer after use. \item[\samp{et} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer]}] Same as \samp{es} except that 8-bit string objects are passed through without recoding them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter. \item[\samp{es\#} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer, int *buffer_length]}] This variant on \samp{s\#} is used for encoding Unicode and objects convertible to Unicode into a character buffer. Unlike the \samp{es} format, this variant allows input data which contains NUL characters. It requires three arguments. The first is only used as input, and must be a \ctype{const char*} which points to the name of an encoding as a NUL-terminated string, or \NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a \ctype{char**}; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer. There are two modes of operation: If \var{*buffer} points a \NULL{} pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set \var{*buffer} to reference the newly allocated storage. The caller is responsible for calling \cfunction{PyMem_Free()} to free the allocated buffer after usage. Lines 1–500 of 1023. Load more
\chapter{Utilities \label{utilities}} The functions in this chapter perform various utility tasks, ranging from helping C code be more portable across platforms, using Python modules from C, and parsing function arguments and constructing Python values from C values. \section{Operating System Utilities \label{os}} \begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, const char *filename} Return true (nonzero) if the standard I/O file \var{fp} with name \var{filename} is deemed interactive. This is the case for files for which \samp{isatty(fileno(\var{fp}))} is true. If the global flag \cdata{Py_InteractiveFlag} is true, this function also returns true if the \var{filename} pointer is \NULL{} or if the name is equal to one of the strings \code{'<stdin>'} or \code{'???'}. \end{cfuncdesc} \begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename} Return the time of last modification of the file \var{filename}. The result is encoded in the same way as the timestamp returned by the standard C library function \cfunction{time()}. \end{cfuncdesc} \begin{cfuncdesc}{void}{PyOS_AfterFork}{} Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. If a new executable is loaded into the new process, this function does not need to be called. \end{cfuncdesc} \begin{cfuncdesc}{int}{PyOS_CheckStack}{} Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when \constant{USE_STACKCHECK} is defined (currently on Windows using the Microsoft Visual \Cpp{} compiler). \constant{USE_STACKCHECK} will be defined automatically; you should never change the definition in your own code. \end{cfuncdesc} \begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i} Return the current signal handler for signal \var{i}. This is a thin wrapper around either \cfunction{sigaction()} or \cfunction{signal()}. Do not call those functions directly! \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}. \end{cfuncdesc} \begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h} Set the signal handler for signal \var{i} to be \var{h}; return the old signal handler. This is a thin wrapper around either \cfunction{sigaction()} or \cfunction{signal()}. Do not call those functions directly! \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}. \end{cfuncdesc} \section{Process Control \label{processControl}} \begin{cfuncdesc}{void}{Py_FatalError}{const char *message} Print a fatal error message and kill the process. No cleanup is performed. This function should only be invoked when a condition is detected that would make it dangerous to continue using the Python interpreter; e.g., when the object administration appears to be corrupted. On \UNIX, the standard C library function \cfunction{abort()}\ttindex{abort()} is called which will attempt to produce a \file{core} file. \end{cfuncdesc} \begin{cfuncdesc}{void}{Py_Exit}{int status} Exit the current process. This calls \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and then calls the standard C library function \code{exit(\var{status})}\ttindex{exit()}. \end{cfuncdesc} \begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()} Register a cleanup function to be called by \cfunction{Py_Finalize()}\ttindex{Py_Finalize()}. The cleanup function will be called with no arguments and should return no value. At most 32 \index{cleanup functions}cleanup functions can be registered. When the registration is successful, \cfunction{Py_AtExit()} returns \code{0}; on failure, it returns \code{-1}. The cleanup function registered last is called first. Each cleanup function will be called at most once. Since Python's internal finalization will have completed before the cleanup function, no Python APIs should be called by \var{func}. \end{cfuncdesc} \section{Importing Modules \label{importing}} \begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{const char *name} This is a simplified interface to \cfunction{PyImport_ImportModuleEx()} below, leaving the \var{globals} and \var{locals} arguments set to \NULL. When the \var{name} argument contains a dot (when it specifies a submodule of a package), the \var{fromlist} argument is set to the list \code{['*']} so that the return value is the named module rather than the top-level package containing it as would otherwise be the case. (Unfortunately, this has an additional side effect when \var{name} in fact specifies a subpackage instead of a submodule: the submodules specified in the package's \code{__all__} variable are \index{package variable!\code{__all__}} \withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a new reference to the imported module, or \NULL{} with an exception set on failure. Before Python 2.4, the module may still be created in the failure case --- examine \code{sys.modules} to find out. Starting with Python 2.4, a failing import of a module no longer leaves the module in \code{sys.modules}. \versionchanged[failing imports remove incomplete module objects]{2.4} \withsubitem{(in module sys)}{\ttindex{modules}} \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist} Import a module. This is best described by referring to the built-in Python function \function{__import__()}\bifuncindex{__import__}, as the standard \function{__import__()} function calls this function directly. The return value is a new reference to the imported module or top-level package, or \NULL{} with an exception set on failure (before Python 2.4, the module may still be created in this case). Like for \function{__import__()}, the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty \var{fromlist} was given. \versionchanged[failing imports remove incomplete module objects]{2.4} \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name} This is a higher-level interface that calls the current ``import hook function''. It invokes the \function{__import__()} function from the \code{__builtins__} of the current globals. This means that the import is done using whatever import hooks are installed in the current environment, e.g. by \module{rexec}\refstmodindex{rexec} or \module{ihooks}\refstmodindex{ihooks}. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m} Reload a module. This is best described by referring to the built-in Python function \function{reload()}\bifuncindex{reload}, as the standard \function{reload()} function calls this function directly. Return a new reference to the reloaded module, or \NULL{} with an exception set on failure (the module still exists in this case). \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{const char *name} Return the module object corresponding to a module name. The \var{name} argument may be of the form \code{package.module}. First check the modules dictionary if there's one there, and if not, create a new one and insert it in the modules dictionary. Return \NULL{} with an exception set on failure. \note{This function does not load or import the module; if the module wasn't already loaded, you will get an empty module object. Use \cfunction{PyImport_ImportModule()} or one of its variants to import a module. Package structures implied by a dotted name for \var{name} are not created if not already present.} \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co} Given a module name (possibly of the form \code{package.module}) and a code object read from a Python bytecode file or obtained from the built-in function \function{compile()}\bifuncindex{compile}, load the module. Return a new reference to the module object, or \NULL{} with an exception set if an error occurred. Before Python 2.4, the module could still be created in error cases. Starting with Python 2.4, \var{name} is removed from \code{sys.modules} in error cases, and even if \var{name} was already in \code{sys.modules} on entry to \cfunction{PyImport_ExecCodeModule()}. Leaving incompletely initialized modules in \code{sys.modules} is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author's intents) state. This function will reload the module if it was already imported. See \cfunction{PyImport_ReloadModule()} for the intended way to reload a module. If \var{name} points to a dotted name of the form \code{package.module}, any package structures not already created will still not be created. \versionchanged[\var{name} is removed from \code{sys.modules} in error cases]{2.4} \end{cfuncdesc} \begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{} Return the magic number for Python bytecode files (a.k.a. \file{.pyc} and \file{.pyo} files). The magic number should be present in the first four bytes of the bytecode file, in little-endian byte order. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{} Return the dictionary used for the module administration (a.k.a.\ \code{sys.modules}). Note that this is a per-interpreter variable. \end{cfuncdesc} \begin{cfuncdesc}{void}{_PyImport_Init}{} Initialize the import mechanism. For internal use only. \end{cfuncdesc} \begin{cfuncdesc}{void}{PyImport_Cleanup}{} Empty the module table. For internal use only. \end{cfuncdesc} \begin{cfuncdesc}{void}{_PyImport_Fini}{} Finalize the import mechanism. For internal use only. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *} For internal use only. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *} For internal use only. \end{cfuncdesc} \begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name} Load a frozen module named \var{name}. Return \code{1} for success, \code{0} if the module is not found, and \code{-1} with an exception set if the initialization failed. To access the imported module on a successful load, use \cfunction{PyImport_ImportModule()}. (Note the misnomer --- this function would reload the module if it was already imported.) \end{cfuncdesc} \begin{ctypedesc}[_frozen]{struct _frozen} This is the structure type definition for frozen module descriptors, as generated by the \program{freeze}\index{freeze utility} utility (see \file{Tools/freeze/} in the Python source distribution). Its definition, found in \file{Include/import.h}, is: \begin{verbatim} struct _frozen { char *name; unsigned char *code; int size; }; \end{verbatim} \end{ctypedesc} \begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules} This pointer is initialized to point to an array of \ctype{struct _frozen} records, terminated by one whose members are all \NULL{} or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules. \end{cvardesc} \begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name, void (*initfunc)(void)} Add a single module to the existing table of built-in modules. This is a convenience wrapper around \cfunction{PyImport_ExtendInittab()}, returning \code{-1} if the table could not be extended. The new module can be imported by the name \var{name}, and uses the function \var{initfunc} as the initialization function called on the first attempted import. This should be called before \cfunction{Py_Initialize()}. \end{cfuncdesc} \begin{ctypedesc}[_inittab]{struct _inittab} Structure describing a single entry in the list of built-in modules. Each of these structures gives the name and initialization function for a module built into the interpreter. Programs which embed Python may use an array of these structures in conjunction with \cfunction{PyImport_ExtendInittab()} to provide additional built-in modules. The structure is defined in \file{Include/import.h} as: \begin{verbatim} struct _inittab { char *name; void (*initfunc)(void); }; \end{verbatim} \end{ctypedesc} \begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab} Add a collection of modules to the table of built-in modules. The \var{newtab} array must end with a sentinel entry which contains \NULL{} for the \member{name} field; failure to provide the sentinel value can result in a memory fault. Returns \code{0} on success or \code{-1} if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the internal table. This should be called before \cfunction{Py_Initialize()}. \end{cfuncdesc} \section{Data marshalling support \label{marshalling-utils}} These routines allow C code to work with serialized objects using the same data format as the \module{marshal} module. There are functions to write data into the serialization format, and additional functions that can be used to read the data back. Files used to store marshalled data must be opened in binary mode. Numeric values are stored with the least significant byte first. The module supports two versions of the data format: version 0 is the historical version, version 1 (new in Python 2.4) shares interned strings in the file, and upon unmarshalling. \var{Py_MARSHAL_VERSION} indicates the current file format (currently 1). \begin{cfuncdesc}{void}{PyMarshal_WriteLongToFile}{long value, FILE *file, int version} Marshal a \ctype{long} integer, \var{value}, to \var{file}. This will only write the least-significant 32 bits of \var{value}; regardless of the size of the native \ctype{long} type. \versionchanged[\var{version} indicates the file format]{2.4} \end{cfuncdesc} \begin{cfuncdesc}{void}{PyMarshal_WriteObjectToFile}{PyObject *value, FILE *file, int version} Marshal a Python object, \var{value}, to \var{file}. \versionchanged[\var{version} indicates the file format]{2.4} \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_WriteObjectToString}{PyObject *value, int version} Return a string object containing the marshalled representation of \var{value}. \versionchanged[\var{version} indicates the file format]{2.4} \end{cfuncdesc} The following functions allow marshalled values to be read back in. XXX What about error detection? It appears that reading past the end of the file will always result in a negative numeric value (where that's relevant), but it's not clear that negative values won't be handled properly when there's no error. What's the right way to tell? Should only non-negative values be written using these routines? \begin{cfuncdesc}{long}{PyMarshal_ReadLongFromFile}{FILE *file} Return a C \ctype{long} from the data stream in a \ctype{FILE*} opened for reading. Only a 32-bit value can be read in using this function, regardless of the native size of \ctype{long}. \end{cfuncdesc} \begin{cfuncdesc}{int}{PyMarshal_ReadShortFromFile}{FILE *file} Return a C \ctype{short} from the data stream in a \ctype{FILE*} opened for reading. Only a 16-bit value can be read in using this function, regardless of the native size of \ctype{short}. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromFile}{FILE *file} Return a Python object from the data stream in a \ctype{FILE*} opened for reading. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadLastObjectFromFile}{FILE *file} Return a Python object from the data stream in a \ctype{FILE*} opened for reading. Unlike \cfunction{PyMarshal_ReadObjectFromFile()}, this function assumes that no further objects will be read from the file, allowing it to aggressively load file data into memory so that the de-serialization can operate from data in memory rather than reading a byte at a time from the file. Only use these variant if you are certain that you won't be reading anything else from the file. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromString}{char *string, Py_ssize_t len} Return a Python object from the data stream in a character buffer containing \var{len} bytes pointed to by \var{string}. On error, sets the appropriate exception (\exception{EOFError} or \exception{TypeError}) and returns \NULL. \end{cfuncdesc} \section{Parsing arguments and building values \label{arg-parsing}} These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in \citetitle[../ext/ext.html]{Extending and Embedding the Python Interpreter}. The first three of these functions described, \cfunction{PyArg_ParseTuple()}, \cfunction{PyArg_ParseTupleAndKeywords()}, and \cfunction{PyArg_Parse()}, all use \emph{format strings} which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. A format string consists of zero or more ``format units.'' A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. \begin{description} \item[\samp{s} (string or Unicode object) {[const char *]}] Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded NUL bytes; if it does, a \exception{TypeError} exception is raised. Unicode objects are converted to C strings using the default encoding. If this conversion fails, a \exception{UnicodeError} is raised. \item[\samp{s\#} (string, Unicode or any read buffer compatible object) {[const char *, int]}] This variant on \samp{s} stores into two C variables, the first one a pointer to a character string, the second one its length. In this case the Python string may contain embedded null bytes. Unicode objects pass back a pointer to the default encoded string version of the object if such a conversion is possible. All other read-buffer compatible objects pass back a reference to the raw internal data representation. \item[\samp{z} (string or \code{None}) {[const char *]}] Like \samp{s}, but the Python object may also be \code{None}, in which case the C pointer is set to \NULL. \item[\samp{z\#} (string or \code{None} or any read buffer compatible object) {[const char *, int]}] This is to \samp{s\#} as \samp{z} is to \samp{s}. \item[\samp{u} (Unicode object) {[Py_UNICODE *]}] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need to provide storage for the Unicode data buffer; a pointer to the existing Unicode data is stored into the \ctype{Py_UNICODE} pointer variable whose address you pass. \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}] This variant on \samp{u} stores into two C variables, the first one a pointer to a Unicode data buffer, the second one its length. Non-Unicode objects are handled by interpreting their read-buffer pointer as pointer to a \ctype{Py_UNICODE} array. \item[\samp{es} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer]}] This variant on \samp{s} is used for encoding Unicode and objects convertible to Unicode into a character buffer. It only works for encoded data without embedded NUL bytes. This format requires two arguments. The first is only used as input, and must be a \ctype{const char*} which points to the name of an encoding as a NUL-terminated string, or \NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a \ctype{char**}; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust \var{*buffer} to reference the newly allocated storage. The caller is responsible for calling \cfunction{PyMem_Free()} to free the allocated buffer after use. \item[\samp{et} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer]}] Same as \samp{es} except that 8-bit string objects are passed through without recoding them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter. \item[\samp{es\#} (string, Unicode object or character buffer compatible object) {[const char *encoding, char **buffer, int *buffer_length]}] This variant on \samp{s\#} is used for encoding Unicode and objects convertible to Unicode into a character buffer. Unlike the \samp{es} format, this variant allows input data which contains NUL characters. It requires three arguments. The first is only used as input, and must be a \ctype{const char*} which points to the name of an encoding as a NUL-terminated string, or \NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a \ctype{char**}; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer. There are two modes of operation: If \var{*buffer} points a \NULL{} pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set \var{*buffer} to reference the newly allocated storage. The caller is responsible for calling \cfunction{PyMem_Free()} to free the allocated buffer after usage.