This recipe shows how to define a new Python class from a C extension module. The class methods are implemented in C, but the class can still be instantiated, extended, subclassed, etc. from Python. The same technique can also be used to extend an existing Python class with methods written in C.
Python, 54 lines
The usual method of creating new types in an extension module is to define a new instance of PyTypeObject and provide callbacks to the various C functions that implement the type. However, it may be better to define the new type as a Python class so that the type can be instantiated, subclassed, etc. from Python. In some cases, defining a custom exception type for instance, it is even required that the new type be a Python class.
The class methods are defined in C functions and described by a table of PyMethodDef's in the same way that module methods are defined. The key that allows these methods to become class methods is that they are each wrapped first in a PyCFunction object and then in a PyMethod object. The PyCFunction turns the C function into a python object, and the PyMethod associates the function with a particular class. Finally, the methods are added to the class' dictionary which makes them callable by instances of the class.
Notes: 1) Base classes can be specified for the new class by passing a tuple of class objects as the first arg to PyClass_New. These can be existing python classes. 2) The second argument passed to PyCFunction_New becomes the "self" arg passed to the C function. This can be any Python object, but it's not very useful in this context since you could just as easily keep a static C variable. 3) The class instance is passed to the C functions as the first argument in the "args" tuple.