languages to run Python program code. In this mode, Python acts as an embedded
control language (what some call a “macro” language). Although embedding is mostly
presented in isolation here, keep in mind that Python’s integration support is best
viewed as a whole. A system’s structure usually determines an appropriate integration
approach: C extensions, embedded code calls, or both. To wrap up, this chapter con-
cludes by discussing a handful of alternative integration platforms such as Jython and
IronPython, which offer broad integration possibilities.
The C Embedding API
The first thing you should know about Python’s embedded-call API is that it is less
structured than the extension interfaces. Embedding Python in C may require a bit
more creativity on your part than extending: you must pick tools from a general col-
lection of calls to implement the Python integration instead of coding to a boilerplate
structure. The upside of this loose structure is that programs can combine embedding
calls and strategies to build up arbitrary integration architectures.
The lack of a more rigid model for embedding is largely the result of a less clear-cut
goal. When extending Python, there is a distinct separation for Python and C respon-
sibilities and a clear structure for the integration. C modules and types are required to
fit the Python module/type model by conforming to standard extension structures. This
makes the integration seamless for Python clients: C extensions look like Python objects
and handle most of the work. It also supports automation tools such as SWIG.
But when Python is embedded, the structure isn’t as obvious; because C is the enclosing
level, there is no clear way to know what model the embedded Python code should fit.
C may want to run objects fetched from modules, strings fetched from files or parsed
out of documents, and so on. Instead of deciding what C can and cannot do, Python
provides a collection of general embedding interface tools, which you use and structure
according to your embedding goals.
Most of these tools correspond to tools available to Python programs. Table 20-1 lists
some of the more common API calls used for embedding, as well as their Python equiv-
alents. In general, if you can figure out how to accomplish your embedding goals in
pure Python code, you can probably find C API tools that achieve the same results.
Table 20-1. Common API functions
C API call Python equivalent
PyImport_ImportModule import module, __import__
PyImport_GetModuleDict sys.modules
PyModule_GetDict module.__dict__
PyDict_GetItemString dict[key]
PyDict_SetItemString dict[key]=val
PyDict_New dict = {}
Embedding Python in C: Overview| 1515