Python: C extensions — sequence-like object

Author:Wojciech Muła
Added on:2011-04-08

If a class has to support standard len() function or operator in, then must be a sequence-like. This requires a variable of type PySequenceMethods, that store addresses of proper functions. Finally the address of this structure have to be assigned to tp_as_sequence member of the main PyTypeObject variable.

Here is a sample code:

static PySequenceMethods class_seq;

static PyTypeObject class_type_dsc = {
        ...
};

ssize_t
classmeth_len(PyObject* self) {
        if (not error)
                return sequence_size;
        else
                return -1;
}

int
classmeth_contains(PyObject* self, PyObject* value) {
        if (not error) {
                if (value in self)
                        return 1;
                else
                        return 0;
        }
        else
                return -1;
}


PyMODINIT_FUNC
PyInit_module() {
        class_seq.sq_length   = classmeth_len;
        class_seq.sq_contains = classmeth_contains;

        class_type_dsc.tp_as_sequence = &class_seq;

        ...
}