13. Subclassing and Using super()

This chapter describes how to subclass existing types and how to call super() in C where necessary.

13.1. Basic Subclassing

In this example we are going to subclass the built in list object and just add a new attribute state. The code is based on Python documentation on subclassing The full code is in src/cpy/SubClass/sublist.c and the tests are in tests/unit/test_c_subclass.py.

13.1.1. Writing the C Extension

First the declaration of the SubListObject:

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct {
    PyListObject list; // The superclass.
    int state;         // Our new attribute.
} SubListObject;

The __init__ method:

static int
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) {
    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) {
        return -1;
    }
    self->state = 0;
    return 0;
}

Now add an increment() method and the method table:

 1static PyObject *
 2SubList_increment(SubListObject *self, PyObject *Py_UNUSED(unused)) {
 3    self->state++;
 4    return PyLong_FromLong(self->state);
 5}
 6
 7static PyMethodDef SubList_methods[] = {
 8        {"increment", (PyCFunction) SubList_increment, METH_NOARGS,
 9                PyDoc_STR("increment state counter")},
10        {NULL, NULL, 0, NULL},
11};

Add the state attribute:

static PyMemberDef SubList_members[] = {
        {"state", T_INT, offsetof(SubListObject, state), 0,
                "Value of the state."},
        {NULL, 0, 0, 0, NULL}  /* Sentinel */
};

Declare the type.

Note that we do not initialise tp_base just yet. The reason is that C99 requires the initializers to be “address constants”. This is best described in the tp_base documentation.

 1static PyTypeObject SubListType = {
 2        PyVarObject_HEAD_INIT(NULL, 0)
 3        .tp_name = "sublist.SubList",
 4        .tp_doc = PyDoc_STR("SubList objects"),
 5        .tp_basicsize = sizeof(SubListObject),
 6        .tp_itemsize = 0,
 7        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
 8        .tp_init = (initproc) SubList_init,
 9        .tp_methods = SubList_methods,
10        .tp_members = SubList_members,
11};

Declare the module:

static PyModuleDef sublistmodule = {
        PyModuleDef_HEAD_INIT,
        .m_name = "sublist",
        .m_doc = "Module that contains a subclass of a list.",
        .m_size = -1,
};

Initialise the module, this is where we set tp_base:

 1PyMODINIT_FUNC
 2PyInit_sublist(void) {
 3    PyObject *m;
 4    SubListType.tp_base = &PyList_Type;
 5    if (PyType_Ready(&SubListType) < 0) {
 6        return NULL;
 7    }
 8    m = PyModule_Create(&sublistmodule);
 9    if (m == NULL) {
10        return NULL;
11    }
12    Py_INCREF(&SubListType);
13    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
14        Py_DECREF(&SubListType);
15        Py_DECREF(m);
16        return NULL;
17    }
18    return m;
19}

13.1.2. Setup and Build

In the setup.py add an Extension such as:

 1Extension(name=f"cPyExtPatt.SubClass.sublist",
 2          include_dirs=[
 3              '/usr/local/include',
 4          ],
 5          sources=[
 6              "src/cpy/SubClass/sublist.c",
 7          ],
 8          extra_compile_args=extra_compile_args_c,
 9          language='c',
10          ),

The extension can be built with python setup.py develop.

13.1.3. Test

The extension can used like this:

from cPyExtPatt.SubClass import sublist

obj = sublist.SubList()
assert obj.state == 0
obj.increment()
assert obj.state == 1

This is fine for subclasses that just add some additional functionality however if you want to overload the super class you need to be able to call super() from C which is described next.

13.2. Calling super() from C

I needed to call super() from a C extension and I couldn’t find a good description of how to do this online so I am including this here. The ability to call super() is needed when you want to modify the behaviour of inherited classes.

Suppose we wanted to subclass a list and record how many times append() was called. This is simple enough in pure Python:

class SubList(list):
    def __init__(self, *args, **kwargs):
        self.appends = 0
        super().__init__(*args, **kwargs)

    def append(self, v):
        self.appends += 1
        return super().append(v)

To do it in C is a bit trickier. Taking as our starting point the example of sub-classing a list in the Python documentation (amended a little bit for our example).

Our type contains an integer count of the number of appends. That is set to zero on construction and can be accessed like a normal member.

 1typedef struct {
 2    PyListObject list;
 3    int appends;
 4} SubListObject;
 5
 6
 7static int
 8SubListObject_init(SubListObject *self, PyObject *args, PyObject *kwds)
 9{
10    if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) {
11        return -1;
12    }
13    self->appends = 0;
14    return 0;
15}
16
17static PyMemberDef SubListObject_members[] = {
18    ...
19    {"appends", T_INT, offsetof(SubListObject, appends), 0,
20        "Number of append operations."},
21    ...
22    {NULL, 0, 0, 0, NULL}  /* Sentinel */
23};

We now need to create the append() function, which will call the superclass append() and then increment the appends counter:

static PyMethodDef SubListObject_methods[] = {
    ...
    {"append", (PyCFunction)SubListObject_append, METH_VARARGS,
        PyDoc_STR("Append to the list")},
    ...
    {NULL,  NULL, 0, NULL},
};

This is where it gets tricky, how do we implement SubListObject_append?

13.2.1. The Obvious Way is Wrong

A first attempt might do something like a method call on the PyListObject:

 1typedef struct {
 2    PyListObject list;
 3    int appends;
 4} SubListObject;
 5
 6/* Other stuff here. */
 7
 8static PyObject *
 9SubListObject_append(SubListObject *self, PyObject *args) {
10    PyObject *result = PyObject_CallMethod((PyObject *)&self->list, "append", "O", args);
11    if (result) {
12        self->appends++;
13    }
14    return result;
15}

This leads to infinite recursion as the address of the first element of a C struct (list) is the address of the struct so self is the same as &self->list. This function is recursive with no base case.

13.2.2. Doing it Right

Our append method needs to use super to search our super-classes for the “append” method and call that.

Here are a couple of ways of calling super() correctly:

  • Construct a super object directly and call that.

  • Extract the super object from the builtins module and call that.

The full code is in src/cpy/Util/py_call_super.h and src/cpy/Util/py_call_super.c.

13.2.2.1. Construct a super object directly

The plan is to do this:

  • Create the arguments to initialise an instance of the class super.

  • Call super.__new__ with those arguments.

  • Call super.__init__ with those arguments.

  • With that super object then search for the method we want to call. This is append in our case. This calls the super_getattro method that performs the search and returns the Python function.

  • Call that Python function and return the result.

Our function is defined thus, for simplicity there is no error checking here. For the full function see below:

 1/* Call func_name on the super classes of self with the arguments and
 2 * keyword arguments.
 3 *
 4 * Equivalent to getattr(super(type(self), self), func_name)(*args, **kwargs)
 5 *
 6 * func_name is a Python string.
 7 * The implementation creates a new super object on each call.
 8 */
 9PyObject *
10call_super_pyname(PyObject *self, PyObject *func_name,
11                  PyObject *args, PyObject *kwargs) {
12    PyObject *super_func = NULL;
13    PyObject *super_args = NULL;
14    PyObject *func = NULL;
15    PyObject *result = NULL;
16
17    // Will be decremented when super_args is decremented if Py_BuildValue succeeds.
18    Py_INCREF(self->ob_type);
19    Py_INCREF(self);
20    super_args = Py_BuildValue("OO", (PyObject *) self->ob_type, self);
21    super_func = PyType_GenericNew(&PySuper_Type, super_args, NULL);
22    // Use tuple as first arg, super() second arg (i.e. kwargs) should be NULL
23    super_func->ob_type->tp_init(super_func, super_args, NULL);
24    func = PyObject_GetAttr(super_func, func_name);
25    result = PyObject_Call(func, args, kwargs);
26    Py_XDECREF(super_func);
27    Py_XDECREF(super_args);
28    Py_XDECREF(func);
29    return result;
30}

We can make this function quite general to be used in the CPython type system. For convenience we can create two functions, one calls the super function by a C NTS, the other by a PyObject string. The following code is essentially the same as above but with error checking.

The header file might be py_call_super.h which just declares our two functions:

 1#ifndef __PythonSubclassList__py_call_super__
 2#define __PythonSubclassList__py_call_super__
 3
 4#include <Python.h>
 5
 6extern PyObject *
 7call_super_pyname(PyObject *self, PyObject *func_name,
 8                  PyObject *args, PyObject *kwargs);
 9extern PyObject *
10call_super_name(PyObject *self, const char *func_cname,
11                PyObject *args, PyObject *kwargs);
12
13#endif /* defined(__PythonSubclassList__py_call_super__) */

And the implementation file would be py_call_super.c, this is the code above with full error checking:

 1/* Call func_name on the super classes of self with the arguments and
 2 * keyword arguments.
 3 *
 4 * Equivalent to getattr(super(type(self), self), func_name)(*args, **kwargs)
 5 *
 6 * func_name is a Python string.
 7 * The implementation creates a new super object on each call.
 8 */
 9PyObject *
10call_super_pyname(PyObject *self, PyObject *func_name,
11                  PyObject *args, PyObject *kwargs) {
12    PyObject *super_func = NULL;
13    PyObject *super_args = NULL;
14    PyObject *func = NULL;
15    PyObject *result = NULL;
16
17    // Error check input
18    if (!PyUnicode_Check(func_name)) {
19        PyErr_Format(PyExc_TypeError,
20                     "super() must be called with unicode attribute not %s",
21                     Py_TYPE(func_name)->tp_name);
22    }
23    // Will be decremented when super_args is decremented if Py_BuildValue succeeds.
24    Py_INCREF(self->ob_type);
25    Py_INCREF(self);
26    super_args = Py_BuildValue("OO", (PyObject *) self->ob_type, self);
27    if (!super_args) {
28        Py_DECREF(self->ob_type);
29        Py_DECREF(self);
30        PyErr_SetString(PyExc_RuntimeError, "Could not create arguments for super().");
31        goto except;
32    }
33    super_func = PyType_GenericNew(&PySuper_Type, super_args, NULL);
34    if (!super_func) {
35        PyErr_SetString(PyExc_RuntimeError, "Could not create super().");
36        goto except;
37    }
38    // Use tuple as first arg, super() second arg (i.e. kwargs) should be NULL
39    super_func->ob_type->tp_init(super_func, super_args, NULL);
40    if (PyErr_Occurred()) {
41        goto except;
42    }
43    func = PyObject_GetAttr(super_func, func_name);
44    if (!func) {
45        assert(PyErr_Occurred());
46        goto except;
47    }
48    if (!PyCallable_Check(func)) {
49        PyErr_Format(PyExc_AttributeError,
50                     "super() attribute \"%S\" is not callable.", func_name);
51        goto except;
52    }
53    result = PyObject_Call(func, args, kwargs);
54    if (!result) {
55        assert(PyErr_Occurred());
56        goto except;
57    }
58    assert(!PyErr_Occurred());
59    goto finally;
60except:
61    assert(PyErr_Occurred());
62    Py_XDECREF(result);
63    result = NULL;
64finally:
65    Py_XDECREF(super_func);
66    Py_XDECREF(super_args);
67    Py_XDECREF(func);
68    return result;
69}

13.2.2.2. Extract the super object from the builtins

Another way to do this is to fish out the super class from the builtins module and use that. Incidentally this is how Cython does it.

The steps are:

  1. Get the builtins module.

  2. Get the super class from the builtins module.

  3. Create a tuple of the arguments to pass to the super class.

  4. Create the super object with the arguments.

  5. Use this super object to call the function with the appropriate function arguments.

Again this code has no error checking for simplicity:

 1extern PyObject *
 2call_super_pyname_lookup(PyObject *self, PyObject *func_name,
 3                         PyObject *args, PyObject *kwargs) {
 4    PyObject *result = NULL;
 5    PyObject *builtins = NULL;
 6    PyObject *super_type = NULL;
 7    PyObject *super = NULL;
 8    PyObject *super_args = NULL;
 9    PyObject *func = NULL;
10
11    builtins = PyImport_AddModule("builtins");
12    // Borrowed reference
13    Py_INCREF(builtins);
14    super_type = PyObject_GetAttrString(builtins, "super");
15    // Will be decremented when super_args is decremented if Py_BuildValue succeeds.
16    Py_INCREF(self->ob_type);
17    Py_INCREF(self);
18    super_args = Py_BuildValue("OO", (PyObject *) self->ob_type, self);
19    super = PyObject_Call(super_type, super_args, NULL);
20    // The following code is the same as call_super_pyname()
21    func = PyObject_GetAttr(super, func_name);
22    result = PyObject_Call(func, args, kwargs);
23    Py_XDECREF(builtins);
24    Py_XDECREF(super_args);
25    Py_XDECREF(super_type);
26    Py_XDECREF(super);
27    Py_XDECREF(func);
28    return result;
29}

Here is the function with full error checking:

 1/* Call func_name on the super classes of self with the arguments and
 2 * keyword arguments.
 3 *
 4 * Equivalent to getattr(super(type(self), self), func_name)(*args, **kwargs)
 5 *
 6 * func_name is a Python string.
 7 * The implementation uses the builtin super().
 8 */
 9extern PyObject *
10call_super_pyname_lookup(PyObject *self, PyObject *func_name,
11                         PyObject *args, PyObject *kwargs) {
12    PyObject *result = NULL;
13    PyObject *builtins = NULL;
14    PyObject *super_type = NULL;
15    PyObject *super = NULL;
16    PyObject *super_args = NULL;
17    PyObject *func = NULL;
18
19    builtins = PyImport_AddModule("builtins");
20    if (!builtins) {
21        assert(PyErr_Occurred());
22        goto except;
23    }
24    // Borrowed reference
25    Py_INCREF(builtins);
26    super_type = PyObject_GetAttrString(builtins, "super");
27    if (!super_type) {
28        assert(PyErr_Occurred());
29        goto except;
30    }
31    // Will be decremented when super_args is decremented if Py_BuildValue succeeds.
32    Py_INCREF(self->ob_type);
33    Py_INCREF(self);
34    super_args = Py_BuildValue("OO", (PyObject *) self->ob_type, self);
35    if (!super_args) {
36        Py_DECREF(self->ob_type);
37        Py_DECREF(self);
38        PyErr_SetString(PyExc_RuntimeError, "Could not create arguments for super().");
39        goto except;
40    }
41    super = PyObject_Call(super_type, super_args, NULL);
42    if (!super) {
43        assert(PyErr_Occurred());
44        goto except;
45    }
46    // The following code is the same as call_super_pyname()
47    func = PyObject_GetAttr(super, func_name);
48    if (!func) {
49        assert(PyErr_Occurred());
50        goto except;
51    }
52    if (!PyCallable_Check(func)) {
53        PyErr_Format(PyExc_AttributeError,
54                     "super() attribute \"%S\" is not callable.", func_name);
55        goto except;
56    }
57    result = PyObject_Call(func, args, kwargs);
58    if (!result) {
59        assert(PyErr_Occurred());
60        goto except;
61    }
62    assert(!PyErr_Occurred());
63    goto finally;
64except:
65    assert(PyErr_Occurred());
66    Py_XDECREF(result);
67    result = NULL;
68finally:
69    Py_XDECREF(builtins);
70    Py_XDECREF(super_args);
71    Py_XDECREF(super_type);
72    Py_XDECREF(super);
73    Py_XDECREF(func);
74    return result;
75}

13.3. Subclassing with Overloading

Lets revisit our subclass of the builtin list that counts how many time append() is called and we will use the C super() API described above.

The full code is in src/cpy/SubClass/sublist.c and the tests are in tests/unit/test_c_subclass.py.

13.3.1. Writing the C Extension

First the declaration and initialisation of SubListObject that has an appends counter. Note the inclusion of py_call_super.h:

 1#define PY_SSIZE_T_CLEAN
 2#include <Python.h>
 3#include "structmember.h"
 4
 5#include "py_call_super.h"
 6
 7typedef struct {
 8    PyListObject list;
 9    int appends;
10} SubListObject;
11
12static int
13SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) {
14    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) {
15        return -1;
16    }
17    self->appends = 0;
18    return 0;
19}

Now the implementation of append that makes the super() call and then increments the appends attribute and returning the value of the super() call:

static PyObject *
SubList_append(SubListObject *self, PyObject *args) {
    PyObject *result = call_super_name((PyObject *)self, "append",
                                       args, NULL);
    if (result) {
        self->appends++;
    }
    return result;
}

The declaration of methods, members and the type:

 1static PyMethodDef SubList_methods[] = {
 2        {"append", (PyCFunction) SubList_append, METH_VARARGS,
 3                PyDoc_STR("append an item")},
 4        {NULL, NULL, 0, NULL},
 5};
 6
 7static PyMemberDef SubList_members[] = {
 8        {"appends", T_INT, offsetof(SubListObject, appends), 0,
 9                "Number of append operations."},
10        {NULL, 0, 0, 0, NULL}  /* Sentinel */
11};
12
13static PyTypeObject SubListType = {
14        PyVarObject_HEAD_INIT(NULL, 0)
15        .tp_name = "sublist.SubList",
16        .tp_doc = PyDoc_STR("SubList objects"),
17        .tp_basicsize = sizeof(SubListObject),
18        .tp_itemsize = 0,
19        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
20        .tp_init = (initproc) SubList_init,
21        .tp_methods = SubList_methods,
22        .tp_members = SubList_members,
23};

Finally the module definition which is very similar to before:

 1static PyModuleDef sublistmodule = {
 2        PyModuleDef_HEAD_INIT,
 3        .m_name = "sublist",
 4        .m_doc = "Module that contains a subclass of a list.",
 5        .m_size = -1,
 6};
 7
 8PyMODINIT_FUNC
 9PyInit_sublist(void) {
10    PyObject *m;
11    SubListType.tp_base = &PyList_Type;
12    if (PyType_Ready(&SubListType) < 0) {
13        return NULL;
14    }
15    m = PyModule_Create(&sublistmodule);
16    if (m == NULL) {
17        return NULL;
18    }
19    Py_INCREF(&SubListType);
20    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
21        Py_DECREF(&SubListType);
22        Py_DECREF(m);
23        return NULL;
24    }
25    return m;
26}

13.3.2. Setup and Build

In the setup.py add an Extension such as:

 1Extension(name=f"cPyExtPatt.SubClass.sublist",
 2          include_dirs=[
 3              '/usr/local/include',
 4          ],
 5          sources=[
 6              "src/cpy/SubClass/sublist.c",
 7          ],
 8          extra_compile_args=extra_compile_args_c,
 9          language='c',
10          ),

The extension can be built with python setup.py develop.

13.3.3. Test

The extension can used like this:

from cPyExtPatt.SubClass import sublist

obj = sublist.SubList()
assert obj.appends == 0
obj.append(42)
assert obj.appends == 1
assert obj == [42, ]

13.3.4. Another Example of Using this API

Here is a real example of using this see overloading replace() when subclassing a datetime in Using an Existing Capsule from the chapter Capsules.

The code here calls the super() function then raises if the given arguments are unacceptable (trying to set the tzinfo property to None):

static PyObject *
DateTimeTZ_replace(PyObject *self, PyObject *args, PyObject *kwargs) {
    PyObject *result = call_super_name(self, "replace", args, kwargs);
    if (result) {
        result = (PyObject *) raise_if_no_tzinfo((DateTimeTZ *) result);
    }
    return result;
}