24.1 Extending Python with Python's C API

A Python extension module named x resides in a dynamic library with the same filename (x.pyd on Windows, x.so on most Unix-like platforms) in an appropriate directory (normally the site-packages subdirectory of the Python library directory). You generally build the x extension module from a C source file x.c with the overall structure:

#include <Python.h>

/* omitted: the body of the x module */

void
initx(void)
{
    /* omitted: the code that initializes the module named x */
}

When you have built and installed the extension module, a Python statement import x loads the dynamic library, then locates and calls the function named initx, which must do all that is needed to initialize the module object named x.

24.1.1 Building and Installing C-Coded Python Extensions

To build and install a C-coded Python extension module, it's simplest and most productive to use the distribution utilities, distutils, covered in Chapter 26. In the same directory as x.c, place a file named setup.py that contains at least the following statements:

from distutils.core import setup, Extension
setup(name='x', ext_modules=[ Extension('x',sources=['x.c']) ])

From a shell prompt in this directory, you can now run:

C:\> python setup.py install

to build the module and install it so that it becomes usable in your Python installation. The distutils perform all needed compilation and linking steps, with the right compiler and linker commands and flags, and copy the resulting dynamic library in an appropriate directory, dependent on your Python installation. Your Python code can then access the resulting module with the statement import x.

24.1.2 Overview of C-Coded Python Extension Modules

Your C function initx generally has the following overall structure:

void
initx(void)
{
    PyObject* thismod = Py_InitModule3("x", x_methods, "docstring for x");
    /* optional: calls to PyModule_AddObject(thismod, "somename", someobj)
       and other Python C API calls to finish preparing module object
       thismod and its types (if any) and other objects.
    */
}

More details are covered in Section 24.1.4 later in this chapter. x_methods is an array of PyMethodDef structs. Each PyMethodDef struct in the x_methods array describes a C function that your module x makes available to Python code that imports x. Each such C function has the following overall structure:

static PyObject*
func_with_named_arguments(PyObject* self, PyObject* args, PyObject* kwds)
{
    /* omitted: body of function, which accesses arguments via the Python C
       API function PyArg_ParseTupleAndKeywords, and returns a PyObject*
       result, NULL for errors */
}

or some simpler variant, such as:

static PyObject*
func_with_positional_args_only(PyObject* self, PyObject* args)
{
    /* omitted: body of function, which accesses arguments via the Python C
       API function PyArg_ParseTuple, and returns a PyObject* result,
       NULL for errors */
}

How C-coded functions access arguments passed by Python code is covered in Section 24.1.6 later in this chapter. How such functions build Python objects is covered in Section 24.1.7, and how they raise or propagate exceptions back to the Python code that called them is covered in Section 24.1.8. When your module defines new Python types (as well as or instead of Python-callable functions), your C code defines one or more instances of struct PyTypeObject. This subject is covered in Section 24.1.12 later in this chapter.

A simple example that makes use of all these concepts is shown in Section 24.1.11 later in this chapter. A toy-level "Hello World" example could be as simple as:

#include <Python.h>

static PyObject*
helloworld(PyObject* self)
{
    return Py_BuildValue("s", "Hello, C-coded Python extensions world!");
}

static char helloworld_docs[] = 
    "helloworld(  ): return a popular greeting phrase\n";

static PyMethodDef helloworld_funcs[] = {
    {"helloworld", (PyCFunction)helloworld, METH_NOARGS, helloworld_docs},
    {NULL}
};

void
inithelloworld(void)
{
    Py_InitModule3("helloworld", helloworld_funcs, 
                   "Toy-level extension module");
}

Save this as helloworld.c, and build it through a setup.py script with distutils. After you have run python setup.py install, you can use the newly installed module, for example from a Python interactive session, such as:

>>> import helloworld
>>> print helloworld.helloworld(  )
Hello, C-coded Python extensions world!
>>>

24.1.3 Return Values of Python's C API Functions

All functions in the Python C API return either an int or a PyObject*. Most functions returning int return 0 in case of success, and -1 to indicate errors. Some functions return results that are true or false: those functions return 0 to indicate false and an integer not equal to 0 to indicate true, and never indicate errors. Functions returning PyObject* return NULL in case of errors. See "Exceptions" later in this chapter for more details on how C-coded functions handle and raise errors.

24.1.4 Module Initialization

Function initx must contain, at a minimum, a call to one of the module initialization functions supplied by the C API. You can always use the Py_InitModule3 function.

Py_InitModule3

PyObject* Py_InitModule3(char* name,PyMethodDef* methods,char* doc)

name is the C string name of the module you are initializing (e.g., "name"). methods is an array of PyMethodDef structures, covered next in this chapter. doc is the C string that becomes the docstring of the module. Py_InitModule3 returns a PyObject* that is a borrowed reference to the new module object, as covered in Section 24.1.5 later in this chapter. In practice, this means that you can ignore the return value if you need to perform no more initialization operations on this module. Otherwise, assign the return value to a C variable of type PyObject* and continue initialization.

Py_InitModule3 initializes the module object to contain the functions described in table methods. Further initialization, if any, may add other module attributes, and is generally best performed with calls to the following convenience functions.

PyModule_AddIntConstant

int PyModule_AddIntConstant(PyObject* module,char* name,int value)

Adds to module module an attribute named name with integer value value.

PyModule_AddObject

int PyModule_AddObject(PyObject* module,char* name,PyObject* value)

Adds to module module an attribute named name with value value and steals a reference to value, as covered in Section 24.1.5.

PyModule_AddStringConstant

int PyModule_AddStringConstant(PyObject* module,char* name,char* value)

Adds to module module an attribute named name with string value value.

Some module initialization operations may be conveniently performed by executing Python code with PyRun_String, covered later in Section 24.3.4, with the module's dictionary as both the globals and locals argument. If you find yourself using PyRun_String extensively, rather than just as an occasional convenience, consider the possibility of splitting your extension module in two: a C-coded extension module offering raw, fast functionality, and a Python module wrapping the C-coded extension to provide further convenience and handy utilities.

When you do need to get a module's dictionary, use the PyModule_GetDict function.

PyModule_GetDict

PyObject* PyModule_GetDict(PyObject* module)

Returns a borrowed reference to the dictionary of module module. You should not use PyModule_GetDict for the specific tasks supported by the PyModule_Add functions covered earlier in this section; I suggest using PyModule_GetDict only for such purposes as supporting the use of PyRun_String.

If you need to access another module, you can import it by calling the PyImport_Import function.

PyImport_Import

PyObject* PyImport_Import(PyObject* name)

Imports the module named in Python string object name and returns a new reference to the module object, like Python's _ _import_ _(name). PyImport_Import is the highest-level, simplest, and most often used way to import a module.

Beware, in particular, of using function PyImport_ImportModule, which may often look more convenient because it accepts a char* argument. PyImport_ImportModule operates on a lower level, bypassing any import hooks that may be in force, so extensions that use it will be far harder to incorporate in packages such as those built by tools py2exe and Installer, covered in Chapter 26. Therefore, always do your importing by calling PyImport_Import, unless you have very specific needs and know exactly what you're doing.

To add functions to a module (or non-special methods to new types, as covered later in Section 24.1.12), you must describe the functions or methods in an array of PyMethodDef structures, and terminate the array with a sentinel (i.e., a structure whose fields are all 0 or NULL). PyMethodDef is defined as follows:

typedef struct {
    char* ml_name;        /* Python name of function or method */
    PyCFunction ml_meth;  /* pointer to C function impl */
    int ml_flags;         /* flag describing how to pass arguments */
    char* ml_doc;         /* docstring for the function or method */
} PyMethodDef

You must cast the second field to (PyCFunction) unless the C function's signature is exactly PyObject* function(PyObject* self, PyObject* args), which is the typedef for PyCFunction. This signature is correct when ml_flags is METH_O, meaning a function that accepts a single argument, or METH_VARARGS, meaning a function that accepts positional arguments. For METH_O, args is the only argument. For METH_VARARGS, args is a tuple of all arguments, to be parsed with the C API function PyArg_ParseTuple. However, ml_flags can also be METH_NOARGS, meaning a function that accepts no arguments, or METH_KEYWORDS, meaning a function that accepts both positional and named arguments. For METH_NOARGS, the signature is PyObject* function(PyObject* self), without arguments. For METH_KEYWORDS, the signature is:

PyObject* function(PyObject* self, PyObject* args, PyObject* kwds)

args is the tuple of positional arguments, and kwds the dictionary of named arguments. args and kwds are parsed together with the C API function PyArg_ParseTupleAndKeywords.

When a C-coded function implements a module's function, the self parameter of the C function is always NULL for any value of the ml_flags field. When a C-coded function implements a non-special method of an extension type, the self parameter points to the instance on which the method is being called.

24.1.5 Reference Counting

Python objects live on the heap, and C code sees them via PyObject*. Each PyObject counts how many references to itself are outstanding, and destroys itself when the number of references goes down to 0. To make this possible, your code must use Python-supplied macros: Py_INCREF to add a reference to a Python object, and Py_DECREF to abandon a reference to a Python object. The Py_XINCREF and Py_XDECREF macros are like Py_INCREF and Py_DECREF, but you may also use them innocuously on a null pointer. The test for a non-null pointer is implicitly performed inside the Py_XINCREF and Py_XDECREF macros, which saves you from needing to write out that test explicitly.

A PyObject* p, which your code receives by calling or being called by other functions, is known as a new reference if the code that supplies p has already called Py_INCREF on your behalf. Otherwise, it is called a borrowed reference. Your code is said to own new references it holds, but not borrowed ones. You can call Py_INCREF on a borrowed reference to make it into a reference that you own; you must do this if you need to use the reference across calls to code that might cause the count of the reference you borrowed to be decremented. You must always call Py_DECREF before abandoning or overwriting references that you own, but never on references you don't own. Therefore, understanding which interactions transfer reference ownership and which ones rely on reference borrowing is absolutely crucial. For most functions in the C API, and for all functions that you write and Python calls, the following general rules apply:

  1. PyObject* arguments are borrowed references

  2. A PyObject* returned as the function's result transfers ownership

For each of the two rules, there are occasional exceptions. PyList_SetItem and PyTuple_SetItem steal a reference to the item they are setting (but not to the list or tuple object into which they're setting it). So do the faster versions of these two functions that exist as C preprocessor macros, PyList_SET_ITEM and PyTuple_SET_ITEM. So does PyModule_AddObject, covered earlier in this chapter. There are no other exceptions to the first rule. The rationale for these exceptions, which may help you remember them, is that the object you're setting is most often one you created for the purpose, so the reference-stealing semantics save you from having to call Py_DECREF immediately afterward.

The second rule has more exceptions than the first one: there are several cases in which the returned PyObject* is a borrowed reference rather than a new reference. The abstract functions, whose names begin with PyObject_, PySequence_, PyMapping_, and PyNumber_, return new references. This is because you can call them on objects of many types, and there might not be any other reference to the resulting object that they return (i.e., the returned object might be created on the fly). The concrete functions, whose names begin with PyList_, PyTuple_, PyDict_, and so on, return a borrowed reference when the semantics of the object they return ensure that there must be some other reference to the returned object somewhere.

In this chapter, I indicate all cases of exceptions to these rules (i.e., the return of borrowed references and the rare cases of reference stealing from arguments) regarding all functions that I cover. When I don't explicitly mention a function as being an exception, it means that the function follows the rules: its PyObject* arguments, if any, are borrowed references, and its PyObject* result, if any, is a new reference.

24.1.6 Accessing Arguments

A function that has ml_flags in its PyMethodDef set to METH_NOARGS is called from Python with no arguments. The corresponding C function has a signature with only one argument, self. When ml_flags is METH_O, Python code must call the function with one argument. The C function's second argument is a borrowed reference to the object that the Python caller passes as the argument's value.

When ml_flags is METH_VARARGS, Python code can call the function with any number of positional arguments, which are collected as a tuple. The C function's second argument is a borrowed reference to the tuple. Your C code can then call the PyArg_ParseTuple function.

PyArg_ParseTuple

int PyArg_ParseTuple(PyObject* tuple,char* format,...)

Returns 0 for errors, a value not equal to 0 for success. tuple is the PyObject* that was the C function's second argument. format is a C string that describes mandatory and optional arguments. The following arguments of PyArg_ParseTuple are the addresses of the C variables in which to put the values extracted from the tuple. Any PyObject* variables among the C variables are borrowed references. Table 24-1 lists the commonly used code strings, of which zero or more are joined to form string format.

Table 24-1. Format codes for PyArg_ParseTuple

Code

C type

Meaning

c
char

A Python string of length 1 becomes a C char

d
double

A Python float becomes a C double

D
Py_Complex

A Python complex becomes a C Py_Complex

f
float

A Python float becomes a C float

i
int

A Python int becomes a C int

l
long

A Python int becomes a C long

L
long long

A Python int becomes a C long long (or _int64 on Windows)

O
PyObject*

Gets non-NULL borrowed reference to a Python argument

O!
type + PyObject*

Like code O, plus type checking or TypeError (see below)

O&
convert + void*

Arbitrary conversion (see below)

s
char*

Python string without embedded nulls to C char*

s#
char* + int

Any Python string to C address and length

t#
char* + int

Read-only single-segment buffer to C address and length

u
Py_UNICODE*

Python Unicode without embedded nulls to C (UTF-16)

u#
Py_UNICODE* + int

Any Python Unicode C (UTF-16) address and length

w#
char* + int

Read-write single-segment buffer to C address and length

z
char*

Like code s, also accepts None (sets C's char* to NULL)

z#
char* + int

Like code s#, also accepts None (sets C's char* to NULL)

(...)

as per ...

A Python sequence is treated as one argument per item

|
 

The following arguments are optional

:
 

Format finished, followed by function name for error messages

;
 

Format finished, followed by entire error message text

Code formats d to L accept numeric arguments from Python. Python coerces the corresponding values. For example, a code of i can correspond to a Python floatthe fractional part gets truncated, as if built-in function int had been called. Py_Complex is a C struct with two fields named real and imag, both of type double.

O is the most general format code and accepts any argument, which you can later check and/or convert as needed. Variant O! corresponds to two arguments in the variable arguments: first the address of a Python type object, then the address of a PyObject*. O! checks that the corresponding value belongs to the given type (or any subtype of that type) before setting the PyObject* to point to the value. Variant O& also corresponds to two arguments in the variable arguments: first the address of a converter function you coded, then a void* (i.e., any address at all). The converter function must have signature int convert(PyObject*, void*). Python calls your conversion function with the value passed from Python as the first argument and the void* from the variable arguments as the second argument. The conversion function must either return 0 and raise an exception (as covered in Section 24.1.8 later in this chapter) to indicate an error, or return 1 and store whatever is appropriate via the void* it gets.

Code format s accepts a string from Python and the address of a char* (i.e., a char**) among the variable arguments. It changes the char* to point at the string's buffer, which your C code must then treat as a read-only, null-terminated array of chars (i.e., a typical C string; however, your code must not modify it). The Python string must contain no embedded null characters. s# is similar, but corresponds to two arguments among the variable arguments: first the address of a char*, then the address of an int to set to the string's length. The Python string can contain embedded nulls, and therefore so can the buffer to which the char* is set to point. u and u# are similar, but accept any Unicode string, and the C-side pointers must be Py_UNICODE* rather than char*. Py_UNICODE is a macro defined in Python.h, and corresponds to the type of a Python Unicode character in the implementation (this is often, but not always, the same as a wchar_t in C).

t# and w# are similar to s#, but the corresponding Python argument can be any object of a type that respects the buffer protocol, respectively read-only and read-write. Strings are a typical example of read-only buffers. mmap and array instances are typical examples of read-write buffers, and they are also acceptable where a read-only buffer is required (i.e., for a t#).

When one of the arguments is a Python sequence of known length, you can use format codes for each of its items, and corresponding C addresses among the variable arguments, by grouping the format codes in parentheses. For example, code (ii) corresponds to a Python sequence of two numbers, and, among the remaining arguments, corresponds to two addresses of ints.

The format string may include a vertical bar (|) to indicate that all following arguments are optional. You must initialize the C variables, whose addresses you pass among the variable arguments for later arguments, to suitable default values before you call PyArg_ParseTuple. PyArg_ParseTuple does not change the C variables corresponding to optional arguments that were not passed in a given call from Python to your C-coded function.

The format string may optionally end with :name to indicate that name must be used as the function name if any error messages are needed. Alternatively, the format string may end with ;text to indicate that text must be used as the entire error message if PyArg_ParseTuple detects errors (this is rarely used).

A function that has ml_flags in its PyMethodDef set to METH_KEYWORDS accepts positional and keyword arguments. Python code calls the function with any number of positional arguments, which get collected as a tuple, and keyword arguments, which get collected as a dictionary. The C function's second argument is a borrowed reference to the tuple, and the third one is a borrowed reference to the dictionary. Your C code then calls the PyArg_ParseTupleAndKeywords function.

PyArg_ParseTupleAndKeywords

int PyArg_ParseTupleAndKeywords(PyObject* tuple,PyObject* dict, 
char* format,char** kwlist,...)

Returns 0 for errors, a value not equal to 0 for success. tuple is the PyObject* that was the C function's second argument. dict is the PyObject* that was the C function's third argument. format is like for PyArg_ParseTuple, except that it cannot include the (...) format code to parse nested sequences. kwlist is an array of char* terminated by a NULL sentinel, with the names of the parameters, one after the other. For example, the following C code:

static PyObject*
func_c(PyObject* self, PyObject* args, PyObject* kwds)
{
    static char* argnames[] = {"x", "y", "z", NULL};
    double x, y=0.0, z=0.0;
    if(!PyArg_ParseTupleAndKeywords(
        args,kwds,"d|dd",argnames,&x,&y,&z))
        return NULL;
    /* rest of function snipped */

is roughly equivalent to this Python code:

def func_py(x, y=0.0, z=0.0):
    x, y, z = map(float, (x,y,z))
    # rest of function snipped

24.1.7 Creating Python Values

C functions that communicate with Python must often build Python values, both to return as their PyObject* result and for other purposes, such as setting items and attributes. The simplest and handiest way to build a Python value is most often with the Py_BuildValue function.

Py_BuildValue

PyObject* Py_BuildValue(char* format,...)

format is a C string that describes the Python object to build. The following arguments of Py_BuildValue are C values from which the result is built. The PyObject* result is a new reference. Table 24-2 lists the commonly used code strings, of which zero or more are joined into string format. Py_BuildValue builds and returns a tuple if format contains two or more format codes, or if format begins with ( and ends with ). Otherwise, the result is not a tuple. When you pass buffers, as for example in the case of format code s#, Py_BuildValue copies the data. You can therefore modify, abandon, or free( ) your original copy of the data after Py_BuildValue returns. Py_BuildValue always returns a new reference (except for format code N). Called with an empty format, Py_BuildValue("") returns a new reference to None.

Table 24-2. Format codes for Py_BuildValue

Code

C type

Meaning

c
char

A C char becomes a Python string of length 1

d
double

A C double becomes a Python float

D
Py_Complex

A C Py_Complex becomes a Python complex

i
int

A C int becomes a Python int

l
long

A C long becomes a Python int

N
PyObject*

Passes a Python object and steals a reference

O
PyObject*

Passes a Python object and INCREFs it as per normal rules

O&
convert + void*

Arbitrary conversion (see below)

s
char*

C null-terminated char* to Python string, or NULL to None

s#
char* + int

C char* and length to Python string, or NULL to None

u
Py_UNICODE*

C wide (UCS-2) null-terminated string to Python Unicode, or NULL to None

u#
Py_UNICODE* + int

C wide (UCS-2) string and length to Python Unicode, or NULL to None

(...)

as per ...

Build Python tuple from C values

[...]

as per ...

Build Python list from C values

{...}

as per ...

Build Python dictionary from C values, alternating keys and values (must be an even number of C values)

Code O& corresponds to two arguments among the variable arguments: first the address of a converter function you code, then a void* (i.e., any address at all). The converter function must have signature PyObject* convert(void*). Python calls the conversion function with the void* from the variable arguments as the only argument. The conversion function must either return NULL and raise an exception (as covered in Section 24.1.8 later in this chapter) to indicate an error, or return a new reference PyObject* built from the data in the void*.

Code {...} builds dictionaries from an even number of C values, alternately keys and values. For example, Py_BuildValue("{issi}",23,"zig","zag",42) returns a dictionary like Python's {23:'zig','zag':42}.

Note the important difference between codes N and O. N steals a reference from the PyObject* corresponding value among the variable arguments, so it's convenient when you're building an object including a reference you own that you would otherwise have to Py_DECREF. O does no reference stealing, so it's appropriate when you're building an object including a reference you don't own, or a reference you must also keep elsewhere.

24.1.8 Exceptions

To propagate exceptions raised from other functions you call, return NULL as the PyObject* result from your C function. To raise your own exceptions, set the current-exception indicator and return NULL. Python's built-in exception classes (covered in Chapter 6) are globally available, with names starting with PyExc_, such as PyExc_AttributeError, PyExc_KeyError, and so on. Your extension module can also supply and use its own exception classes. The most commonly used C API functions related to raising exceptions are the following.

PyErr_Format

PyObject* PyErr_Format(PyObject* type,char* format,...)

Raises an exception of class type, a built-in such as PyExc_IndexError, or an exception class created with PyErr_NewException. Builds the associated value from format string format, which has syntax similar to printf's, and the following C values indicated as variable arguments above. Returns NULL, so your code can just call:

return PyErr_Format(PyExc_KeyError, 
    "Unknown key name (%s)", thekeystring);
PyErr_NewException

PyObject* PyErr_NewException(char* name,PyObject* base,PyObject* dict)

Subclasses exception class base, with extra class attributes and methods from dictionary dict (normally NULL, meaning no extra class attributes or methods), creating a new exception class named name (string name must be of the form "modulename.classname") and returning a new reference to the new class object. When base is NULL, uses PyExc_Exception as the base class. You normally call this function during initialization of a module object module. For example:

PyModule_AddObject(module, "error", 
    PyErr_NewException("mymod.error", NULL, NULL));
PyErr_NoMemory

PyObject* PyErr_NoMemory(  )

Raises an out-of-memory error and returns NULL, so your code can just call:

return PyErr_NoMemory(  );
PyErr_SetObject

void PyErr_SetObject(PyObject* type,PyObject* value)

Raises an exception of class type, a built-in such as PyExc_KeyError, or an exception class created with PyErr_NewException, with value as the associated value (a borrowed reference). PyErr_SetObject is a void function (i.e., returns no value).

PyErr_SetFromErrno

PyObject* PyErr_SetFromErrno(PyObject* type)

Raises an exception of class type, a built-in such as PyExc_OSError, or an exception class created with PyErr_NewException. Takes all details from global variable errno, which C library functions and system calls set for many error cases, and the standard C library function strerror. Returns NULL, so your code can just call:

return PyErr_SetFromErrno(PyExc_IOError);
PyErr_SetFromErrnoWithFilename

PyObject* PyErr_SetFromErrnoWithFilename(PyObject* type,char* filename)

Like PyErr_SetFromErrno, but also provides string filename as part of the exception's value. When filename is NULL, works like PyErr_SetFromErrno.

Your C code may want to deal with an exception and continue, as a try/except statement would let you do in Python code. The most commonly used C API functions related to catching exceptions are the following.

PyErr_Clear

void PyErr_Clear(  )

Clears the error indicator. Innocuous if no error is pending.

PyErr_ExceptionMatches

int PyErr_ExceptionMatches(PyObject* type)

Call only when an error is pending, or the whole program might crash. Returns a value not equal to 0 when the pending exception is an instance of the given type or any subclass of type, or 0 when the pending exception is not such an instance.

PyErr_Occurred

PyObject* PyErr_Occurred(  )

Returns NULL if no error is pending, otherwise a borrowed reference to the type of the pending exception. (Don't use the returned value; call PyErr_ExceptionMatches instead, in order to catch exceptions of subclasses as well, as is normal and expected.)

PyErr_Print

void PyErr_Print(  )

Call only when an error is pending, or the whole program might crash. Outputs a standard traceback to sys.stderr, then clears the error indicator.

If you need to process errors in highly sophisticated ways, study other error-related functions of the C API, such as PyErr_Fetch, PyErr_Normalize, PyErr_GivenExceptionMatches, and PyErr_Restore. However, I do not cover such advanced and rarely needed possibilities in this book.

24.1.9 Abstract Layer Functions

The code for a C extension typically needs to use some Python functionality. For example, your code may need to examine or set attributes and items of Python objects, call Python-coded and built-in functions and methods, and so on. In most cases, the best approach is for your code to call functions from the abstract layer of Python's C API. These are functions that you can call on any Python object (functions whose names start with PyObject_), or any object within a wide category, such as mappings, numbers, or sequences (with names respectively starting with PyMapping_, PyNumber_, and PySequence_).

Some of the functions callable on objects within these categories duplicate functionality that is also available from PyObject_ functions; in these cases, you should use the PyObject_ function instead. I don't cover such redundant functions in this book.

Functions in the abstract layer raise Python exceptions if you call them on objects to which they are not applicable. All of these functions accept borrowed references for PyObject* arguments, and return a new reference (NULL for an exception) if they return a PyObject* result.

The most frequently used abstract layer functions are the following.

PyCallable_Check

int PyCallable_Check(PyObject* x)

True if x is callable, like Python's callable(x).

PyEval_CallObject

PyObject* PyEval_CallObject(PyObject* x,PyObject* args)

Calls callable Python object x with the positional arguments held in tuple args. Returns the call's result, like Python's return x(*args).

PyEval_CallObjectWithKeywords

PyObject* PyEval_CallObjectWithKeywords(PyObject* x,PyObject* args,PyObject* kwds)

Calls callable Python object x with the positional arguments held in tuple args and the named arguments held in dictionary kwds Returns the call's result, like Python's return x(*args,**kwds).

PyIter_Check

int PyIter_Check(PyObject* x)

True if x supports the iterator protocol (i.e., if x is an iterator).

PyIter_Next

PyObject* PyIter_Next(PyObject* x)

Returns the next item from iterator x. Returns NULL without raising any exception if x's iteration is finished (i.e., when Python's x.next( ) raises StopIteration).

PyNumber_Check

int PyNumber_Check(PyObject* x)

True if x supports the number protocol (i.e., if x is a number).

PyObject_CallFunction

PyObject* PyObject_CallFunction(PyObject* x,char* format,...)

Calls the callable Python object x with positional arguments described by format string format, using the same format codes as Py_BuildValue, covered earlier. When format is NULL, calls x with no arguments. Returns the call's result.

PyObject_CallMethod

PyObject* PyObject_CallMethod(PyObject* x,char* method,char* format,...)

Calls the method named method of Python object x with positional arguments described by format string format, using the same format codes as Py_BuildValue. When format is NULL, calls the method with no arguments. Returns the call's result.

PyObject_Cmp

int PyObject_Cmp(PyObject* x1,PyObject* x2,int* result)

Compares objects x1 and x2 and places the result (-1, 0, or 1) in *result, like Python's result=cmp(x1,x2).

PyObject_DelAttrString

int PyObject_DelAttrString(PyObject* x,char* name)

Deletes x's attribute named name, like Python's del x.name.

PyObject_DelItem

int PyObject_DelItem(PyObject* x,PyObject* key)

Deletes x's item with key (or index) key, like Python's del x[key].

PyObject_DelItemString

int PyObject_DelItemString(PyObject* x,char* key)

Deletes x's item with key key, like Python's del x[key].

PyObject_GetAttrString

PyObject* PyObject_GetAttrString(PyObject* x,char* name)

Returns x's attribute named name, like Python's x.name.

PyObject_GetItem

PyObject* PyObject_GetItem(PyObject* x,PyObject* key)

Returns x's item with key (or index) key, like Python's x[key].

PyObject_GetItemString

int PyObject_GetItemString(PyObject* x,char* key)

Returns x's item with key key, like Python's x[key].

PyObject_GetIter

PyObject* PyObject_GetIter(PyObject* x)

Returns an iterator on x, like Python's iter(x).

PyObject_HasAttrString

int PyObject_HasAttrString(PyObject* x,char* name)

True if x has an attribute named name, like Python's hasattr(x,name).

PyObject_IsTrue

int PyObject_IsTrue(PyObject* x)

True if x is true for Python, like Python's bool(x).

PyObject_Length

int PyObject_Length(PyObject* x)

Returns x's length, like Python's len(x).

PyObject_Repr

PyObject* PyObject_Repr(PyObject* x)

Returns x's detailed string representation, like Python's repr(x).

PyObject_RichCompare

PyObject* PyObject_RichCompare(PyObject* x,PyObject* y,int op)

Performs the comparison indicated by op between x and y, and returns the result as a Python object. op can be Py_EQ, Py_NE, Py_LT<



Part III: Python Library and Extension Modules