2.5 A Sketch of the Python/C API

There is no way a tutorial document like this can or should cover every aspect of the Python/C API. This section aims to give you some pointers for what you should do when you find yourself needing to know something not described in this document.

The two main sources of information are, perhaps predictably, the API reference manual and the source of Python itself.

The Python/C API is divided into at least three layers: the ``very high'', ``abstract objects'' and ``concrete objects'' layers, together with a few other areas.

The very high level interface is mostly about executing Python source code contained in files or C strings. It is more useful when embedding than when extending Python.

The abstract objects layer contains functions that interact with objects irrespective of their type, or across a wide range of types such as ``all sequence types''. Most functions in this API perform operations that also be executed from Python: if all your extension does is call abstract layer functions, there's likely no reason for it not being a Python module instead! Such a C extension is not likely to be very much quicker than the corresponding Python module, and certainly a good deal more tedious to write. It's good practice, however, to use abstract objects layer functions to handle objects that are passed in as arguments to your functions; for example, it's friendlier to accept any sequence type as opposed to insisting on lists.

The concrete layer deals with particular types of Python object - dicts, ints, tuples and so on. Which of these functions you are most likely to need corresponds fairly closely to the types you use often in Python, and also to those that most closely correspond to C types. It's a rare extension module that doesn't use an integer-related function; it's an even rarer one that explicitly manipulates PyGetSetDescrObjects. A frequent use of concrete layer functions is assembling objects for returning to Python; if an object has been created by a call to PyList_New you can be certain that it's a list, and using a generic sequence function to fill it out is just pointless.

Not all of the API fits into these layers; there are also functions for importing modules, dealing with exceptions and the unpacking and packing functions that have already been described.

Another part of the API consists not of functions but of structure definitions, of which by far the most important

THIS DOCUMENT IS A DRAFT! Comments to mwh@python.net please.