5. Struct Sequence (a namedtuple in C)

A Struct Sequence Object object is, more or less, the C equivalent of Python’s namedtuple type [1].

As a reminder here is how named tuples work in Python:

>>> from collections import namedtuple
>>> nt_type = namedtuple('MyNamedTuple', ['field_one', 'field_two'])
>>> nt_type
<class '__main__.MyNamedTuple'>
>>> nt_type._fields
('field_one', 'field_two')
>>> nt = nt_type(['foo', 'bar'])
>>> nt.field_one
'foo'
>>> nt.index('bar')
1

The C Struct Sequence API allows you to define and create Struct Sequence Objects within C but act (almost) like collections.namedtuple objects. These are very useful in creating the equivalent of a C struct in Python.

5.1. Differences Between a C Struct Sequence and a Python namedtuple

Unlike a Python namedtuple a C Struct Sequence does not have the following functions and attributes (the official Python documentation does not point this out):

Struct Sequence Objects also differ from namedtuples in the way that members can be accessed. namedtuples can access all their members either by name or by index. A Struct Sequence Object can be designed so that any attribute can be accessed by either name or index or both (or even neither!).

5.2. A Basic C Struct Sequence

Here is an example of defining a Struct Sequence in C (the code is in src/cpy/StructSequence/cStructSequence.c).

5.2.1. Documentation String

First create a named documentation string:

PyDoc_STRVAR(
    BasicNT_docstring,
    "A basic named tuple type with two fields."
);

5.2.2. Field Specifications

Now create the field definitions as an array of PyStructSequence_Field. These are just pairs of {field_name, field_description}:

static PyStructSequence_Field BasicNT_fields[] = {
    {"field_one", "The first field of the named tuple."},
    {"field_two", "The second field of the named tuple."},
    {NULL, NULL}
};

5.2.3. Struct Sequence Type Specification

Now create the PyStructSequence_Desc that is a name, documentation, fields and the number of fields visible in Python. The latter value is explained later but for the moment make it the number of declared fields.

static PyStructSequence_Desc BasicNT_desc = {
    "cStructSequence.BasicNT",
    BasicNT_docstring,
    BasicNT_fields,
    2,
};

Note

If the given number of fields (n_in_sequence) is greater than the length of the fields array then PyStructSequence_NewType() will return NULL.

There is a test example of this dbg_PyStructSequence_n_in_sequence_too_large() in src/cpy/Containers/DebugContainers.c.

5.2.4. Creating an Instance

Here is a function BasicNT_create() that creates a Struct Sequence from arguments provided from a Python session. Things to note:

Note

The careful use of Py_INCREF when setting the fields.

 1static PyObject *
 2BasicNT_create(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
 3    assert(!PyErr_Occurred());
 4    static char *kwlist[] = {"field_one", "field_two", NULL};
 5    PyObject *field_one = NULL;
 6    PyObject *field_two = NULL;
 7    static PyTypeObject *static_BasicNT_Type = NULL;
 8
 9    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &field_one, &field_two)) {
10        return NULL;
11    }
12    /* The two fields are PyObjects. If your design is that those arguments should be
13     * specific types then take the opportunity here to test that they are the
14     * expected types.
15     */
16
17    /* Now check that the type is available. */
18    if (!static_BasicNT_Type) {
19        static_BasicNT_Type = PyStructSequence_NewType(&BasicNT_desc);
20        if (!static_BasicNT_Type) {
21            PyErr_SetString(
22                    PyExc_MemoryError,
23                    "Can not initialise a BasicNT type with PyStructSequence_NewType()"
24            );
25            return NULL;
26        }
27    }
28    PyObject *result = PyStructSequence_New(static_BasicNT_Type);
29    if (!result) {
30        PyErr_SetString(
31                PyExc_MemoryError,
32                "Can not create a Struct Sequence with PyStructSequence_New()"
33        );
34        return NULL;
35    }
36    /* PyArg_ParseTupleAndKeywords with "O" gives a borrowed reference.
37     * https://docs.python.org/3/c-api/arg.html#other-objects
38     * "A new strong reference to the object is not created
39     * (i.e. its reference count is not increased)."
40     *
41     * So we increment as PyStructSequence_SetItem seals the reference otherwise
42     * if the callers arguments goes out of scope we will/may get undefined behaviour
43     * when accessing the named tuple fields.
44     */
45    Py_INCREF(field_one);
46    Py_INCREF(field_two);
47    PyStructSequence_SetItem(result, 0, field_one);
48    PyStructSequence_SetItem(result, 1, field_two);
49    return result;
50}

This function is then added to the cStructSequence module like this:

static PyMethodDef cStructSequence_methods[] = {
    /* More stuff here... */
    {
        "BasicNT_create",
        (PyCFunction) BasicNT_create,
        METH_VARARGS | METH_KEYWORDS,
        "Create a BasicNT from the given values."
    },
    /* More stuff here... */
    {NULL, NULL, 0, NULL} /* Sentinel */
};

5.2.5. Using an Instance

And can be used like this:

from cPyExtPatt import cStructSequence

def test_basic_nt_create():
    basic_nt = cStructSequence.BasicNT_create('foo', 'bar')
    assert str(type(basic_nt)) == "<class 'cStructSequence.BasicNT'>"


def test_basic_nt_create_attributes():
    basic_nt = cStructSequence.BasicNT_create('foo', 'bar')
    assert basic_nt.field_one == "foo"
    assert basic_nt.field_two == "bar"
    assert basic_nt.index("foo") == 0
    assert basic_nt.index("bar") == 1
    assert basic_nt.n_fields == 2
    assert basic_nt.n_sequence_fields == 2
    assert basic_nt.n_unnamed_fields == 0

5.3. Whether to Provide Access to the Type from Python

One decision to be made is whether to expose your Struct Sequence type from the module. There are only two use cases for this:

  • Do you want the user to be able to create your Struct Sequence/namedtuple directly from Python? In which case then you need to expose the type of your Struct Sequence from the module. Then anyone can create these objects directly from Python.

  • If the objects are created only in C then you do not need to expose the type in the module but you can create functions the create those Python objects (and their types) dynamically.

Firstly, exposing the Struct Sequence type to Python.

5.3.1. Exposing the Type from the CPython Module

In this case the Struct Sequence can be created from Python (as well as from C).

For example here is a simple Struct Sequence cStructSequence.NTRegistered that contains two fields.

First, creating the documentation:

PyDoc_STRVAR(
        NTRegistered_docstring,
        "A namedtuple type with two fields that is"
        "registered with the cStructSequence module."
);

Defining the fields, this is an array of PyStructSequence_Field which are pairs of {field_name, field_documentation} (both strings) and terminated with a NULL sentinel:

static PyStructSequence_Field NTRegistered_fields[] = {
        {"field_one", "The first field of the namedtuple."},
        {"field_two", "The second field of the namedtuple."},
        {NULL, NULL}
};

Creating the Struct Sequence description that will define the type. This is a PyStructSequence_Desc that consists of:

  • The Struct Sequence name, this must include the module name so is of the form "module_name.struct_sequence_name":

  • The documentation string.

  • The fields as an array of PyStructSequence_Field.

  • The number of fields exposed to Python.

static PyStructSequence_Desc NTRegistered_desc = {
        "cStructSequence.NTRegistered",
        NTRegistered_docstring,
        NTRegistered_fields,
        2,
};

Then the module initialisation code looks like this, this uses PyStructSequence_NewType() to create the type:

PyMODINIT_FUNC
PyInit_cStructSequence(void) {
    PyObject *m;
    m = PyModule_Create(&cStructSequence_cmodule);
    if (m == NULL) {
        return NULL;
    }
    /* Initialise NTRegisteredType */
    PyObject *NTRegisteredType = (PyObject *) PyStructSequence_NewType(
        &NTRegistered_desc
    );
    if (NTRegisteredType == NULL) {
        Py_DECREF(m);
        return NULL;
    }
    Py_INCREF(NTRegisteredType);
    PyModule_AddObject(m, "NTRegisteredType", NTRegisteredType);

    /*
     * Other module initialisation code here.
     */

    return m;
}

This can be used thus in Python:

from cPyExtPatt import cStructSequence

nt = cStructSequence.NTRegisteredType(('foo', 'bar'))
assert str(nt) == "cStructSequence.NTRegistered(field_one='foo', field_two='bar')"

There are tests for this in tests/unit/test_c_struct_sequence.py.

5.3.2. Hiding the Type in the Module

In this case the Struct Sequence can be not be created from Python, only in C. Even though the constructor is not accessible from Python the type is, as we will see.

For example here is a simple Struct Sequence cStructSequence.NTUnRegistered that contains two fields. It is, initially, very similar to the above.

PyDoc_STRVAR(
        NTUnRegistered_docstring,
        "A namedtuple type with two fields that is"
        " not registered with the cStructSequence module."
);

static PyStructSequence_Field NTUnRegistered_fields[] = {
        {"field_one", "The first field of the namedtuple."},
        {"field_two", "The second field of the namedtuple."},
        {NULL, NULL}
};

static PyStructSequence_Desc NTUnRegistered_desc = {
        "cStructSequence.NTUnRegistered",
        NTUnRegistered_docstring,
        NTUnRegistered_fields,
        2,
};

However as the type is not initialised in the module definition it remains static to the module C code. It is, as yet, uninitialised:

/* Type initailised dynamically by NTUnRegistered_create(). */
static PyTypeObject *static_NTUnRegisteredType = NULL;

This type, and objects created from it, can be made with a function call, in this case taking variable and keyword arguments:

 1/* A function that creates a cStructSequence.NTUnRegistered dynamically. */
 2PyObject *
 3NTUnRegistered_create(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
 4    assert(!PyErr_Occurred());
 5    static char *kwlist[] = {"field_one", "field_two", NULL};
 6    PyObject *field_one = NULL;
 7    PyObject *field_two = NULL;
 8
 9    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &field_one, &field_two)) {
10        return NULL;
11    }
12    /* The two fields are PyObjects. If your design is that those arguments should be
13     * specific types then take the opportunity here to test that they are the
14     * expected types.
15     */
16
17    /* Initialise the static static_NTUnRegisteredType.
18     * Note: PyStructSequence_NewType returns a new reference.
19     */
20    if (!static_NTUnRegisteredType) {
21        static_NTUnRegisteredType = PyStructSequence_NewType(&NTUnRegistered_desc);
22        if (!static_NTUnRegisteredType) {
23            PyErr_SetString(
24                PyExc_MemoryError,
25                "Can not initialise a type with PyStructSequence_NewType()"
26            );
27            return NULL;
28        }
29    }
30    PyObject *result = PyStructSequence_New(static_NTUnRegisteredType);
31    if (!result) {
32        PyErr_SetString(
33            PyExc_MemoryError,
34            "Can not create a Struct Sequence with PyStructSequence_New()"
35        );
36        return NULL;
37    }
38    /* PyArg_ParseTupleAndKeywords with "O" gives a borrowed reference.
39     * https://docs.python.org/3/c-api/arg.html#other-objects
40     * "A new strong reference to the object is not created
41     * (i.e. its reference count is not increased)."
42     * So we increment as PyStructSequence_SetItem seals the reference otherwise if
43     * the callers arguments go out of scope we will/may get undefined behaviour when
44     * accessing the namedtuple fields.
45     */
46    Py_INCREF(field_one);
47    Py_INCREF(field_two);
48    PyStructSequence_SetItem(result, 0, field_one);
49    PyStructSequence_SetItem(result, 1, field_two);
50    return result;
51}

And this can be used thus:

from cPyExtPatt import cStructSequence

ntu = cStructSequence.NTUnRegistered_create('foo', 'bar')
# Note that the type is available
assert str(type(ntu)) == "<class 'cStructSequence.NTUnRegistered'>"

A common use of this is converting a C struct to a Python namedtuple.

5.4. Converting a C struct to a namedtuple

A common use case for not exposing the namedtuple type from the module is when the data object can only be created in C. Suppose that we have a simple struct representing a transaction.

/**
 * Representation of a simple transaction.
 */
struct cTransaction {
    long id;            /* The transaction id. */
    char *reference;    /* The transaction reference. */
    double amount;      /* The transaction amount. */
};

And we have a C function that can recover a transaction given its ID:

/**
 * An example function that might recover a transaction from within C code,
 * possibly a C library.
 * In practice this will actually do something more useful that this function does!
 *
 * @param id The transaction ID.
 * @return A struct cTransaction corresponding to the transaction ID.
 */
static struct cTransaction get_transaction(long id) {
    struct cTransaction ret = {id, "Some reference.", 42.76};
    return ret;
}

Then we create a namedtuple type that mirrors the C struct Transaction:

PyDoc_STRVAR(
    cTransaction_docstring,
    "Example of a named tuple type representing a transaction created in C."
    " The type is not registered with the cStructSequence module."
);

static PyStructSequence_Field cTransaction_fields[] = {
        {"id", "The transaction id."},
        {"reference", "The transaction reference."},
        {"amount", "The transaction amount."},
        {NULL, NULL}
};

static PyStructSequence_Desc cTransaction_desc = {
        "cStructSequence.cTransaction",
        cTransaction_docstring,
        cTransaction_fields,
        3,
};

This Python type is declared static and initialised dynamically when necessary. As this might be used by multiple functions so we give it an API:

/* Type initialised dynamically by get_cTransactionType(). */
static PyTypeObject *static_cTransactionType = NULL;

static PyTypeObject *get_cTransactionType(void) {
    if (static_cTransactionType == NULL) {
        static_cTransactionType = PyStructSequence_NewType(&cTransaction_desc);
        if (static_cTransactionType == NULL) {
            PyErr_SetString(
                PyExc_MemoryError,
                "Can not initialise a cTransaction type with PyStructSequence_NewType()"
            );
            return NULL;
        }
    }
    return static_cTransactionType;
}

Now the Python/C interface function:

/* A function that creates a cStructSequence.NTUnRegistered dynamically. */
PyObject *
cTransaction_get(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
    assert(!PyErr_Occurred());
    static char *kwlist[] = {"id", NULL};
    long id = 0l;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "l", kwlist, &id)) {
        return NULL;
    }
    PyObject *result = PyStructSequence_New(get_cTransactionType());
    if (!result) {
        assert(PyErr_Occurred());
        return NULL;
    }

    struct cTransaction transaction = get_transaction(id);
    PyStructSequence_SetItem(result, 0, PyLong_FromLong(transaction.id));
    PyStructSequence_SetItem(result, 1, PyUnicode_FromString(transaction.reference));
    PyStructSequence_SetItem(result, 2, PyFloat_FromDouble(transaction.amount));
    return result;
}

Add to the module methods:

static PyMethodDef cStructSequence_methods[] = {
    /* Other stuff... */
    {
        "cTransaction_get",
        (PyCFunction) cTransaction_get,
        METH_VARARGS | METH_KEYWORDS,
        "Example of getting a transaction."
    },
    /* Other stuff... */
    {NULL, NULL, 0, NULL} /* Sentinel */
};

And then this can be called from Python like this:

nt = cStructSequence.cTransaction_get(17145)
assert nt.id == 17145
assert nt.reference == "Some reference."
assert nt.amount == 42.76

5.5. Controlling Member Access

Struct Sequence Objects differ from namedtuples in the way that members can be accessed. A Struct Sequence Object can be designed so that any attribute can be accessed by either name or index or both (or even neither!). This describes how to do this.

5.5.1. The Importance of the n_in_sequence Field

PyStructSequence_Desc has a field n_in_sequence which needs some explaining (the Python documentation is pretty silent on this). Normally n_in_sequence is equal to the number of fields, however what happens if it is not?

5.5.1.1. n_in_sequence > Number of Fields

As mentioned above if the given number of fields (n_in_sequence) is greater than the length of the fields array then PyStructSequence_NewType() will return NULL.

There is a test example of this dbg_PyStructSequence_n_in_sequence_too_large() in src/cpy/Containers/DebugContainers.c.

5.5.1.2. n_in_sequence < Number of Fields

In this case the members with an index >= n_in_sequence will raise an IndexError. However that same member can always be accessed from Python by name.

There some illustrative tests test_excess_nt_* in tests/unit/test_c_struct_sequence.py for this.

5.6. Unnamed Fields

The Struct Sequence C API provides for having unnamed fields. These are fields unavailable to Python code but available to C code. The rules using these are quite involved and the Python documentation is poor at describing them so I’ll do my best here.

Note

Unnamed fields does not appear to work in Python versions prior to 3.11 with the following compile time error:

E   ImportError: dlopen(... cStructSequence.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_PyStructSequence_UnnamedField'

The rules appear to be:

Failing to follow the rules will cause a SystemError when you use repr() or str() such as:

SystemError: In structseq_repr(), member 2 name is NULL for type module.struct_sequence_simple_with_unnamed_field

PyStructSequence_UnnamedField is the sentinel that describes the ‘name’ of the unnamed field. However you can not use it directly when declaring a PyStructSequence_Field:

static PyStructSequence_Field NTWithUnnamedField_fields[] = {
        {"field_one", "The first field of the named tuple."},
        {PyStructSequence_UnnamedField, "Documentation for an unnamed field."},
        {NULL, NULL}
};

This will fail with a compilation error along the lines of:

cStructSequence.c:391:10: fatal error: initializer element is not a compile-time constant
        {PyStructSequence_UnnamedField, "Documentation for an unnamed field."},
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Instead declare the field name as NULL:

static PyStructSequence_Field NTWithUnnamedField_fields[] = {
    {"field_one",   "The first field of the named tuple."},
    /* Use NULL then replace with PyStructSequence_UnnamedField
     * otherwise get an error "initializer element is not a compile-time constant" */
    {NULL,          "Documentation for an unnamed field."},
    {NULL, NULL}
};

Then before the type is used the NULL needs to be replaced with PyStructSequence_UnnamedField. Here is the complete code that demonstrates initialising a static Struct Sequence type static_NTWithUnnamedField_Type.

5.6.1. Field Declaration

First declare the fields:

static PyStructSequence_Field NTWithUnnamedField_fields[] = {
    {"field_one",   "The first field of the named tuple."},
    /* Use NULL then replace with PyStructSequence_UnnamedField
     * otherwise get an error "initializer element is not a compile-time constant" */
    {NULL,          "Documentation for an unnamed field."},
    {NULL, NULL}
};

Then the field description:

PyDoc_STRVAR(
    NTWithUnnamedField_docstring,
    "A basic named tuple type with an unnamed field."
);

static PyStructSequence_Desc NTWithUnnamedField_desc = {
    "cStructSequence.NTWithUnnamedField",
    NTWithUnnamedField_docstring,
    NTWithUnnamedField_fields,
    1, /* Of two fields only one available to Python by name. */
};

5.6.2. Type Declaration

Now the Struct Sequence type, for convenience the static is accessed with a getter that also serves as an initialisation function:

static PyTypeObject *static_NTWithUnnamedField_Type = NULL;

/**
 * Initialises and returns the \c NTWithUnnamedField_Type.
 * @return The initialised type.
 */
static PyTypeObject *get_NTWithUnnamedField_Type(void) {
    if (!static_NTWithUnnamedField_Type) {
        /* Substitute PyStructSequence_UnnamedField for NULL. */
        NTWithUnnamedField_fields[1].name = PyStructSequence_UnnamedField;
        /* Create and initialise the type. */
        static_NTWithUnnamedField_Type = PyStructSequence_NewType(
            &NTWithUnnamedField_desc
        );
        if (!static_NTWithUnnamedField_Type) {
            PyErr_SetString(
                PyExc_RuntimeError,
                "Can not initialise a NTWithUnnamedField type with PyStructSequence_NewType()"
            );
            return NULL;
        }
    }
    return static_NTWithUnnamedField_Type;
}

5.6.3. Struct Sequence Creation

Here is the constructor that takes three arguments:

 1static PyObject *
 2NTWithUnnamedField_create(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
 3    assert(!PyErr_Occurred());
 4    static char *kwlist[] = {"field_one", "field_two", "field_three", NULL};
 5    PyObject *field_one = NULL;
 6    PyObject *field_two = NULL;
 7    PyObject *field_three = NULL;
 8
 9    if (
10        !PyArg_ParseTupleAndKeywords(
11            args, kwds, "OOO", kwlist, &field_one, &field_two, &field_three
12        )
13    ) {
14        return NULL;
15    }
16    /* The three fields are PyObjects.
17     *  If your design is that those arguments should be specific types
18     * then take the opportunity here to test that they are the expected types.
19     */
20
21    PyObject *result = PyStructSequence_New(get_NTWithUnnamedField_Type());
22    if (!result) {
23        PyErr_SetString(
24                PyExc_RuntimeError,
25                "Can not create a NTWithUnnamedField Struct"
26                " Sequence with PyStructSequence_New()"
27        );
28        return NULL;
29    }
30    /* PyArg_ParseTupleAndKeywords with "O" gives a borrowed reference.
31     * https://docs.python.org/3/c-api/arg.html#other-objects
32     * "A new strong reference to the object is not created
33     * (i.e. its reference count is not increased)."
34     * So we increment as PyStructSequence_SetItem seals the reference otherwise
35     * if the callers arguments go out of scope we will/may get undefined
36     * behaviour when accessing the named tuple fields.
37     */
38    Py_INCREF(field_one);
39    Py_INCREF(field_two);
40    Py_INCREF(field_three);
41    PyStructSequence_SetItem(result, 0, field_one);
42    PyStructSequence_SetItem(result, 1, field_two);
43    PyStructSequence_SetItem(result, 2, field_three);
44    assert(!PyErr_Occurred());
45    return result;
46}

5.6.4. Access from Python

Once built this can be accessed from Python (see tests/unit/test_c_struct_sequence.py):

from cPyExtPatt import cStructSequence

ntuf = cStructSequence.NTWithUnnamedField_create('foo', 'bar', 'baz')
# All these tests are True
assert len(ntuf) == 1
assert ntuf.n_fields == 2
assert ntuf.n_sequence_fields == 1
assert ntuf.n_unnamed_fields == 1
assert tuple(ntuf) == ('foo',)
assert ntuf[0] == 'foo'
# Will raise an IndexError: 'tuple index out of range'
with pytest.raises(IndexError) as err:
    assert ntuf[1] == 'bar'
assert repr(ntuf) == "cStructSequence.NTWithUnnamedField(field_one='foo')"
assert str(ntuf) == "cStructSequence.NTWithUnnamedField(field_one='foo')"

Footnotes