15. Iterators and Generators

This chapter describes how to write iterators for your C objects. These iterators allow your objects to be used with a Generator.

15.1. Iterators

The iterator concept is actually fairly straight forward:

  • You have some object that contains some data.

  • You have some iterator that traverses the data.

That iterator:

  • Has a strong reference to the originating object, thus its data. This strong reference keeps the originating object alive as long as the iterator is alive.

  • It has a notion of state, in other words ‘where I was before so know where to go next’.

Warning

The strong reference to the underlying data structure keeps it alive but what happens if the underlying structure is altered during iteration?

Here is an example:

lst = list(range(8))
for i, value in enumerate(lst):
    print(f'i={i} value={value}')
    del lst[i]

This gives the sequence:

i=0 value=0
i=1 value=2
i=2 value=4
i=3 value=6

Which may not be what you want. It is hard to make a ‘good’ design to cope with this (defer the del? raise?) so the general advice is: do not alter the underlying structure whilst iterating.

15.1.1. Example of a Sequence

In this example we create a module that has an object which holds a sequence of C long s. The complete code is in src/cpy/Iterators/cIterator.c here are just the essential parts. The test code is in tests/unit/test_c_iterators.py.

Essentially in Python this means I will be able do this:

from cPyExtPatt.Iterators import cIterator

sequence = cIterator.SequenceOfLong([1, 7, 4])
result = [v for v in sequence]
assert result == [1, 7, 4]

Note

Because of the entwined nature of the sequence object and the iterator object the code in src/cpy/Iterators/cIterator.c occasionally appears out of order.

Firstly, here is the C declaration of the SequenceOfLong struct:

 1#define PY_SSIZE_T_CLEAN
 2
 3#include <Python.h>
 4#include "structmember.h"
 5
 6typedef struct {
 7    PyObject_HEAD
 8    long *array_long;
 9    size_t size;
10} SequenceOfLong;

This will be instantiated with a Python sequence of integers:

 1static PyObject *
 2SequenceOfLong_new(PyTypeObject *type, PyObject *Py_UNUSED(args),
 3                   PyObject *Py_UNUSED(kwds)) {
 4    SequenceOfLong *self;
 5    self = (SequenceOfLong *) type->tp_alloc(type, 0);
 6    if (self != NULL) {
 7        assert(!PyErr_Occurred());
 8        self->size = 0;
 9        self->array_long = NULL;
10    }
11    return (PyObject *) self;
12}

And initialised with a Python sequence of integers:

Note

The use of the Sequence Protocol API such as PySequence_Length() and PySequence_GetItem()

 1static int
 2SequenceOfLong_init(SequenceOfLong *self, PyObject *args, PyObject *kwds) {
 3    static char *kwlist[] = {"sequence", NULL};
 4    PyObject *sequence = NULL;
 5
 6    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &sequence)) {
 7        return -1;
 8    }
 9    if (!PySequence_Check(sequence)) {
10        return -2;
11    }
12    self->size = PySequence_Length(sequence);
13    self->array_long = malloc(self->size * sizeof(long));
14    if (! self->array_long) {
15        return -3;
16    }
17    for (Py_ssize_t i = 0; i < PySequence_Length(sequence); ++i) {
18        // New reference.
19        PyObject *py_value = PySequence_GetItem(sequence, i);
20        if (PyLong_Check(py_value)) {
21            self->array_long[i] = PyLong_AsLong(py_value);
22            Py_DECREF(py_value);
23        } else {
24            PyErr_Format(
25                    PyExc_TypeError,
26                    "Argument [%zd] must be a int, not type %s",
27                    i,
28                    Py_TYPE(sequence)->tp_name
29            );
30            // Clean up on error.
31            free(self->array_long);
32            self->array_long = NULL;
33            Py_DECREF(py_value);
34            return -4;
35        }
36    }
37    return 0;
38}

And the de-allocation function frees the dynamically allocated memory:

static void
SequenceOfLong_dealloc(SequenceOfLong *self) {
    free(self->array_long);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

We provide a single method size() for the length of the sequence and a __str__ method:

 1SequenceOfLong_size(SequenceOfLong *self, PyObject *Py_UNUSED(ignored)) {
 2    return Py_BuildValue("n", self->size);
 3}
 4
 5static PyMethodDef SequenceOfLong_methods[] = {
 6        {
 7            "size",
 8            (PyCFunction) SequenceOfLong_size,
 9            METH_NOARGS,
10            "Return the size of the sequence."
11        },
12        {NULL, NULL, 0, NULL}  /* Sentinel */
13};
14
15static PyObject *
16SequenceOfLong___str__(SequenceOfLong *self, PyObject *Py_UNUSED(ignored)) {
17    assert(!PyErr_Occurred());
18    return PyUnicode_FromFormat("<SequenceOfLong sequence size: %ld>", self->size);
19}

The type declaration then becomes:

 1static PyTypeObject SequenceOfLongType= {
 2        PyVarObject_HEAD_INIT(NULL, 0)
 3        .tp_name = "SequenceOfLong",
 4        .tp_basicsize = sizeof(SequenceOfLong),
 5        .tp_itemsize = 0,
 6        .tp_dealloc = (destructor) SequenceOfLong_dealloc,
 7        .tp_str = (reprfunc) SequenceOfLong___str__,
 8        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
 9        .tp_doc = "Sequence of long integers.",
10        .tp_methods = SequenceOfLong_methods,
11        .tp_init = (initproc) SequenceOfLong_init,
12        .tp_new = SequenceOfLong_new,
13};

This will be used thus:

from cPyExtPatt.Iterators import cIterator

sequence = cIterator.SequenceOfLong([1, 7, 4])

But we can’t (yet) iterate across the sequence. To do that we need to add an iterator.

15.1.2. Adding an Iterator

Here is the iterator that takes a reference to the SequenceOfLong and maintains an index:

typedef struct {
    PyObject_HEAD
    PyObject *sequence;
    size_t index;
} SequenceOfLongIterator;

Here are the __new__, __init__ and de-allocation methods:

 1static PyObject *
 2SequenceOfLongIterator_new(PyTypeObject *type, PyObject *Py_UNUSED(args),
 3                           PyObject *Py_UNUSED(kwds)) {
 4    SequenceOfLongIterator *self;
 5    self = (SequenceOfLongIterator *) type->tp_alloc(type, 0);
 6    if (self != NULL) {
 7        assert(!PyErr_Occurred());
 8    }
 9    return (PyObject *) self;
10}
11
12// Forward reference
13static int is_sequence_of_long_type(PyObject *op);
14// Defined later to be:
15// static int
16// is_sequence_of_long_type(PyObject *op) {
17//      return Py_TYPE(op) == &SequenceOfLongType;
18// }

Here is the initialisation function, note the line Py_INCREF(sequence); that keeps the original sequence alive.

 1static int
 2SequenceOfLongIterator_init(SequenceOfLongIterator *self, PyObject *args,
 3                            PyObject *kwds) {
 4    static char *kwlist[] = {"sequence", NULL};
 5    PyObject *sequence = NULL;
 6    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &sequence)) {
 7        return -1;
 8    }
 9    if (!is_sequence_of_long_type(sequence)) {
10        PyErr_Format(
11                PyExc_ValueError,
12                "Argument must be a SequenceOfLongType, not type %s",
13                Py_TYPE(sequence)->tp_name
14                );
15        return -2;
16    }
17    // Borrowed reference
18    // Keep the sequence alive as long as the iterator is alive.
19    // Decrement on iterator de-allocation.
20    Py_INCREF(sequence);
21    self->sequence = sequence;
22    self->index = 0;
23    return 0;
24}

Here is the de-allocation function once the iterator is deleted. Note the line Py_XDECREF(self->sequence); that allows the original sequence to be free’d.

static void
SequenceOfLongIterator_dealloc(SequenceOfLongIterator *self) {
    // Decrement borrowed reference.
    Py_XDECREF(self->sequence);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

Here is the __next__ method. This returns the next object in the sequence, or NULL if the sequence is exhausted. It updates the internal counter on each call:

 1static PyObject *
 2SequenceOfLongIterator_next(SequenceOfLongIterator *self) {
 3    size_t size = ((SequenceOfLong *) self->sequence)->size;
 4    if (self->index < size) {
 5        PyObject *ret = PyLong_FromLong(
 6            ((SequenceOfLong *) self->sequence)->array_long[self->index]
 7        );
 8        self->index += 1;
 9        return ret;
10    }
11    // End iteration.
12    return NULL;
13}

Here is the iterator type declaration, note the use of tp_iter and tp_iternext.

  • tp_iter signals that this object is an iterable and its result is the iterator. The use of PyObject_SelfIter merely says “I am an iterator”.

  • tp_iternext is the function to call with the iterator as its sole argument and this returns the next item in the sequence.

Note

PyObject_SelfIter() is a supported CPython API and is implemented thus:

PyObject *
PyObject_SelfIter(PyObject *obj)
{
    Py_INCREF(obj);
    return obj;
}

Here is the type declaration for the iterator, the iterator is both iterable and has a __next__ method so both tp_iter and tp_iternext are defined:

 1static PyTypeObject SequenceOfLongIteratorType = {
 2        PyVarObject_HEAD_INIT(NULL, 0)
 3        .tp_name = "SequenceOfLongIterator",
 4        .tp_basicsize = sizeof(SequenceOfLongIterator),
 5        .tp_itemsize = 0,
 6        .tp_dealloc = (destructor) SequenceOfLongIterator_dealloc,
 7        .tp_str = (reprfunc) SequenceOfLongIterator___str__,
 8        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
 9        .tp_doc = "SequenceOfLongIterator object.",
10        .tp_iter = PyObject_SelfIter,
11        .tp_iternext = (iternextfunc) SequenceOfLongIterator_next,
12        .tp_init = (initproc) SequenceOfLongIterator_init,
13        .tp_new = SequenceOfLongIterator_new,
14};

Now change the type declaration of the SequenceOfLongType to add iteration. This defines tp_iter as it is iterable but does not define the tp_iternext method as it does not have a __next__ method, the iterator instance provides that:

 1static PyTypeObject SequenceOfLongType= {
 2        PyVarObject_HEAD_INIT(NULL, 0)
 3        .tp_name = "SequenceOfLong",
 4        .tp_basicsize = sizeof(SequenceOfLong),
 5        .tp_itemsize = 0,
 6        .tp_dealloc = (destructor) SequenceOfLong_dealloc,
 7        .tp_str = (reprfunc) SequenceOfLong___str__,
 8        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
 9        .tp_doc = "Sequence of long integers.",
10        // I am iterable, this function gives you an iterator on me.
11        .tp_iter = (getiterfunc) SequenceOfLong_iter,
12        .tp_methods = SequenceOfLong_methods,
13        .tp_init = (initproc) SequenceOfLong_init,
14        .tp_new = SequenceOfLong_new,
15};

15.1.3. A Note on Module Initialisation

The module initialisation looks like this:

PyMODINIT_FUNC
PyInit_cIterator(void) {
    PyObject *m;
    m = PyModule_Create(&iterator_cmodule);
    if (m == NULL) {
        return NULL;
    }
    // ...
}

Naturally enough we have to include the initialisation of SequenceOfLongType:

 1if (PyType_Ready(&SequenceOfLongType) < 0) {
 2    Py_DECREF(m);
 3    return NULL;
 4}
 5Py_INCREF(&SequenceOfLongType);
 6if (PyModule_AddObject(
 7        m,
 8        "SequenceOfLong",
 9        (PyObject *) &SequenceOfLongType) < 0
10        ) {
11    Py_DECREF(&SequenceOfLongType);
12    Py_DECREF(m);
13    return NULL;
14}

We must include the initialisation of SequenceOfLongIteratorType:

if (PyType_Ready(&SequenceOfLongIteratorType) < 0) {
    Py_DECREF(m);
    return NULL;
}
Py_INCREF(&SequenceOfLongIteratorType);

However the following is optional, as the comment suggests:

 1// Not strictly necessary unless you need to expose this type.
 2// For type checking for example.
 3if (PyModule_AddObject(
 4        m,
 5        "SequenceOfLongIterator",
 6        (PyObject *) &SequenceOfLongIteratorType) < 0
 7        ) {
 8    Py_DECREF(&SequenceOfLongType);
 9    Py_DECREF(&SequenceOfLongIteratorType);
10    Py_DECREF(m);
11    return NULL;
12}

If you omit that the code will work just fine, the iterator is instantiated dynamically, it is just that the type is not exposed from the module.

15.1.4. Iterating a Python Object in C

In src/cpy/Iterators/cIterator.c there is an example of iterating a Python object using the Iterator Protocol. There is a function iterate_and_print that takes an object supporting the Iterator Protocol and iterates across it printing out each item.

The equivalent Python code is:

def iterate_and_print(sequence: typing.Iterable) -> None:
    print('iterate_and_print:')
    for i, item in enumerate(sequence):
        print(f'[{i}]: {item}')
    print('iterate_and_print: DONE')

The C code looks like this:

 1static PyObject *
 2iterate_and_print(PyObject *Py_UNUSED(module), PyObject *args, PyObject *kwds) {
 3    assert(!PyErr_Occurred());
 4    static char *kwlist[] = {"sequence", NULL};
 5    PyObject *sequence = NULL;
 6
 7    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &sequence)) {
 8        return NULL;
 9    }
10    PyObject *iterator = PyObject_GetIter(sequence);
11    if (iterator == NULL) {
12        /* propagate error */
13        assert(PyErr_Occurred());
14        return NULL;
15    }
16    PyObject *item = NULL;
17    long index = 0;
18    fprintf(stdout, "%s:\n", __FUNCTION__ );
19    while ((item = PyIter_Next(iterator))) {
20        /* do something with item */
21        fprintf(stdout, "[%ld]: ", index);
22        if (PyObject_Print(item, stdout, Py_PRINT_RAW) == -1) {
23            /* Handle error. */
24            Py_DECREF(item);
25            Py_DECREF(iterator);
26            if (!PyErr_Occurred()) {
27                PyErr_Format(PyExc_RuntimeError,
28                             "Can not print an item of type %s",
29                             Py_TYPE(sequence)->tp_name);
30            }
31            return NULL;
32        }
33        fprintf(stdout, "\n");
34        ++index;
35        /* release reference when done */
36        Py_DECREF(item);
37    }
38    Py_DECREF(iterator);
39    if (PyErr_Occurred()) {
40        /* propagate error */
41        return NULL;
42    }
43    fprintf(stdout, "%s: DONE\n", __FUNCTION__ );
44    assert(!PyErr_Occurred());
45    Py_RETURN_NONE;
46}

This function is added to the cIterator module thus:

 1static PyMethodDef cIterator_methods[] = {
 2        {"iterate_and_print", (PyCFunction) iterate_and_print, METH_VARARGS,
 3         "Iterate through the argument printing the values."},
 4        {NULL, NULL, 0, NULL} /* Sentinel */
 5};
 6
 7static PyModuleDef iterator_cmodule = {
 8        PyModuleDef_HEAD_INIT,
 9        .m_name = "cIterator",
10        .m_doc = (
11                "Example module that creates an extension type"
12                "that has forward and reverse iterators."
13        ),
14        .m_size = -1,
15        .m_methods = cIterator_methods,
16};

An example of using this is shown below.

15.1.5. Examples

Now we can import the module, and create a sequence:

from cPyExtPatt.Iterators import cIterator

sequence = cIterator.SequenceOfLong([1, 7, 4])

And these calls now work:

result = [v for v in sequence]
assert result == [1, 7, 4]

Delete the underlying object, the iteration still works:

iterator = iter(sequence)
del sequence
result = [v for v in iterator]
assert result == [1, 7, 4]

Using the builtin next():

iterator = iter(sequence)
assert next(iterator) == 1
assert next(iterator) == 7
assert next(iterator) == 4
# next() will raise a StopIteration.

Using the builtin sorted():

sequence = cIterator.SequenceOfLong([1, 7, 4])
result = sorted(sequence)
assert result == [1, 4, 7, ]

And to iterate across a Python object:

cIterator.iterate_and_print('abc')

Result in the stdout:

iterate_and_print:
[0]: a
[1]: b
[2]: c
iterate_and_print: DONE

Note

If you are running under pytest you can capture the output to stdout from C using the capfd fixture:

 1import pytest
 2
 3@pytest.mark.parametrize(
 4    'arg, expected',
 5    (
 6            (
 7                    'abc',
 8                    """iterate_and_print:
 9[0]: a
10[1]: b
11[2]: c
12iterate_and_print: DONE
13"""
14            ),
15    )
16)
17def test_iterate_and_print(arg, expected, capfd):
18    cIterator.iterate_and_print(arg)
19    captured = capfd.readouterr()
20    assert captured.out == expected

15.1.6. Reverse Iterators

If we try and use the reversed() function on our current SequenceOfLong we will get an error:

TypeError: 'SequenceOfLong' object is not reversible

Reverse iterators are slightly unusual, the reversed() function calls the object __reversed__() method if available or falls back on using __len__() and __getitem__().

reversed() acts like this python code:

 1def reversed(obj: object):
 2    if hasattr(obj, '__reversed__'):
 3        yield from obj.__reversed__()
 4    elif hasattr(obj, '__len__') and hasattr(obj, '__getitem__'):
 5        i = len(obj) - 1
 6        while i >= 0:
 7            yield obj[i]
 8            i -= 1
 9    else:
10        raise TypeError(f'{type(object)} is not reversible')

To support this in C we can implement __len__() and __getitem__() using the PySequenceMethods method table.

First the implementation of __len__() in C:

static Py_ssize_t
SequenceOfLong_sq_length(PyObject *self) {
    return ((SequenceOfLong *)self)->size;
}

Then the implementation of __getitem__(), note here that we support negative indexes and set and exception if the index is out of range:

 1static PyObject *
 2SequenceOfLong_sq_item(PyObject *self, Py_ssize_t index) {
 3    Py_ssize_t my_index = index;
 4    if (my_index < 0) {
 5        my_index += SequenceOfLong_sq_length(self);
 6    }
 7    if (my_index > SequenceOfLong_sq_length(self)) {
 8        PyErr_Format(
 9            PyExc_IndexError,
10            "Index %ld is out of range for length %ld",
11            index,
12            SequenceOfLong_sq_length(self)
13        );
14        return NULL;
15    }
16    return PyLong_FromLong(((SequenceOfLong *)self)->array_long[my_index]);
17}

Create PySequenceMethods method table:

PySequenceMethods SequenceOfLong_sequence_methods = {
    .sq_length = &SequenceOfLong_sq_length,
    .sq_item = &SequenceOfLong_sq_item,
};

Add this method table into the type specification:

static PyTypeObject SequenceOfLongType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    /* Other stuff. */
    .tp_dealloc = (destructor) SequenceOfLong_dealloc,
    .tp_as_sequence = &SequenceOfLong_sequence_methods,
    /* Other stuff. */
};

And we can test it thus:

def test_c_iterator_reversed():
    sequence = cIterator.SequenceOfLong([1, 7, 4])
    result = reversed(sequence)
    assert list(result) == [4, 7, 1,]

15.2. Generators

Iterators are a requirement for Generators, the secret weapon in Pythons toolbox. If you don’t believe me then ask David Beazley who has done some very fine and informative presentations on Generators

15.2.1. Our Iterator as a Generator

Now we have an iterator we can write generator:

def yield_from_an_iterator_times_two(iterator):
    for value in iterator:
        yield 2 * value

And test it:

def test_c_iterator_yield_forward():
    sequence = cIterator.SequenceOfLong([1, 7, 4])
    iterator = iter(sequence)
    result = []
    for v in yield_from_an_iterator_times_two(iterator):
        result.append(v)
    assert result == [2, 14, 8]

And create a generator expression:

sequence = cIterator.SequenceOfLong([1, 7, 4])
result = sum(v * 4 for v in sequence)
assert result == 4 * (1 + 7 + 4)