9. Creating New Types

The creation of new extension types (AKA ‘classes’) is pretty well described in the Python documentation tutorial and reference. This section is a cookbook of tricks and examples.

9.1. Properties

9.1.1. Referencing Existing Properties

If the property is part of the extension type then it is fairly easy to make it directly accessible as described here

Note

Terminology

In this section “property”, “attribute” and “field” are used interchangeably.

For example the Noddy struct has a Python object (a Python string) and a C object (an C int):

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    /* ... */
    int number;
} Noddy;

These can be exposed by identifying them as members with an array of PyMemberDef like this:

static PyMemberDef Noddy_members[] = {
    {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
     "first name"},
    /* ... */
    {"number", T_INT, offsetof(Noddy, number), 0,
     "noddy number"},
    {NULL}  /* Sentinel */
};

And the type struct must reference this array of PyMemberDef thus:

static PyTypeObject NoddyType = {
    /* ... */
    Noddy_members,             /* tp_members */
    /* ... */
};

Reference to PyMemberdef.

9.1.2. Created Properties

If the properties are not directly accessible, for example they might need to be created, then an array of PyGetSetDef structures is used in the PyTypeObject.tp_getset slot.

 1static PyObject*
 2Foo_property_getter(Foo* self, void * /* closure */) {
 3    return /* ... */;
 4}
 5
 6int
 7Foo_property_setter(Foo* self, PyObject *value) {
 8    return /* 0 on success, -1 on failure with error set. */;
 9}
10
11static PyGetSetDef Foo_properties[] = {
12    {"id", (getter) Foo_property_getter, (setter) Foo_property_setter,
13        "The property documentation.", NULL },
14    {NULL}  /* Sentinel */
15};

And the type struct must reference this array of PyMemberDef thus:

static PyTypeObject FooType = {
    /* ... */
    Foo_properties,             /* tp_getset */
    /* ... */
};

Reference to PyGetSetDef.

9.2. Subclassing

This large subject gets it own chapter: Subclassing and Using super().

9.3. Examples

See src/cpy/cObject.c for some examples, the tests for these are in tests/unit/test_c_object.py:

  • Null is a basic class that does nothing.

  • Str is a subclass of the builtin str class.

9.3.1. Setting, Getting and Deleting Attributes Dynamically

In src/cpy/cObject.c there is an example, ObjectWithAttributes, which is a class that can set, get, delete attributes dynamically.

Firstly the object declaration:

typedef struct {
    PyObject_HEAD
    /* Attributes dictionary, NULL on construction,
     * will be populated by MyObj_getattro. */
    PyObject *x_attr;
} ObjectWithAttributes;

Then some type checking that requires a forward declaration:

/** Forward declaration. */
static PyTypeObject ObjectWithAttributes_Type;
#define ObjectWithAttributes_Check(v) (Py_TYPE(v) == &ObjectWithAttributes_Type)

The __new__ and __del__ methods:

 1static ObjectWithAttributes *
 2ObjectWithAttributes_new(PyObject *Py_UNUSED(arg)) {
 3    ObjectWithAttributes *self;
 4    self = PyObject_New(ObjectWithAttributes, &ObjectWithAttributes_Type);
 5    if (self == NULL) {
 6        return NULL;
 7    }
 8    self->x_attr = NULL;
 9    return self;
10}
11
12/* ObjectWithAttributes methods */
13static void
14ObjectWithAttributes_dealloc(ObjectWithAttributes *self) {
15    Py_XDECREF(self->x_attr);
16    PyObject_Del(self);
17}

Add an empty method for demonstration:

 1static PyObject *
 2ObjectWithAttributes_demo(ObjectWithAttributes *Py_UNUSED(self), PyObject *args) {
 3    if (!PyArg_ParseTuple(args, ":demo")) {
 4        return NULL;
 5    }
 6    Py_INCREF(Py_None);
 7    return Py_None;
 8}
 9
10static PyMethodDef ObjectWithAttributes_methods[] = {
11        {"demo", (PyCFunction) ObjectWithAttributes_demo, METH_VARARGS,
12                        PyDoc_STR("demo() -> None")},
13        {NULL, NULL, 0, NULL} /* sentinel */
14};

Now the methods to get and set attribute:

 1static PyObject *
 2ObjectWithAttributes_getattro(ObjectWithAttributes *self, PyObject *name) {
 3    if (self->x_attr != NULL) {
 4        PyObject *v = PyDict_GetItem(self->x_attr, name);
 5        if (v != NULL) {
 6            Py_INCREF(v);
 7            return v;
 8        }
 9    }
10    return PyObject_GenericGetAttr((PyObject *) self, name);
11}
12
13static int
14ObjectWithAttributes_setattr(ObjectWithAttributes *self, char *name, PyObject *v) {
15    if (self->x_attr == NULL) {
16        self->x_attr = PyDict_New();
17        if (self->x_attr == NULL)
18            return -1;
19    }
20    if (v == NULL) {
21        int rv = PyDict_DelItemString(self->x_attr, name);
22        if (rv < 0)
23            PyErr_SetString(PyExc_AttributeError,
24                            "delete non-existing ObjectWithAttributes attribute");
25        return rv;
26    } else
27        /* v is a borrowed reference,
28         * then PyDict_SetItemString() does NOT steal it
29         * so nothing to do. */
30        return PyDict_SetItemString(self->x_attr, name, v);
31}

Finally the type declaration. Note this is the complete type declaration with compiler declarations to suit Python versions 3.6 to 3.13:

 1static PyTypeObject ObjectWithAttributes_Type = {
 2        /* The ob_type field must be initialized in the module init function
 3         * to be portable to Windows without using C++. */
 4        PyVarObject_HEAD_INIT(NULL, 0)
 5        "cObject.ObjectWithAttributes",             /*tp_name*/
 6        sizeof(ObjectWithAttributes),          /*tp_basicsize*/
 7        0,                          /*tp_itemsize*/
 8        /* methods */
 9        (destructor) ObjectWithAttributes_dealloc,    /*tp_dealloc*/
10#if PY_MINOR_VERSION < 8
11        0,                          /*tp_print*/
12#else
13        0,                          /* Py_ssize_t tp_vectorcall_offset; */
14#endif
15        (getattrfunc) 0,             /*tp_getattr*/
16        (setattrfunc) ObjectWithAttributes_setattr,   /*tp_setattr*/
17        0,                          /*tp_reserved*/
18        0,                          /*tp_repr*/
19        0,                          /*tp_as_number*/
20        0,                          /*tp_as_sequence*/
21        0,                          /*tp_as_mapping*/
22        0,                          /*tp_hash*/
23        0,                          /*tp_call*/
24        0,                          /*tp_str*/
25        (getattrofunc) ObjectWithAttributes_getattro, /*tp_getattro*/
26        0,                          /*tp_setattro*/
27        0,                          /*tp_as_buffer*/
28        Py_TPFLAGS_DEFAULT,         /*tp_flags*/
29        0,                          /*tp_doc*/
30        0,                          /*tp_traverse*/
31        0,                          /*tp_clear*/
32        0,                          /*tp_richcompare*/
33        0,                          /*tp_weaklistoffset*/
34        0,                          /*tp_iter*/
35        0,                          /*tp_iternext*/
36        ObjectWithAttributes_methods,                /*tp_methods*/
37        0,                          /*tp_members*/
38        0,                          /*tp_getset*/
39        0,                          /*tp_base*/
40        0,                          /*tp_dict*/
41        0,                          /*tp_descr_get*/
42        0,                          /*tp_descr_set*/
43        0,                          /*tp_dictoffset*/
44        0,                          /*tp_init*/
45        0,                          /*tp_alloc*/
46//    PyType_GenericNew,          /*tp_new*/
47        (newfunc) ObjectWithAttributes_new,          /*tp_new*/
48        0,                          /*tp_free*/
49        0,                          /*tp_is_gc*/
50        NULL,                   /* tp_bases */
51        NULL,                   /* tp_mro */
52        NULL,                   /* tp_cache */
53        NULL,               /* tp_subclasses */
54        NULL,                    /* tp_weaklist */
55        NULL,                       /* tp_del */
56        0,                  /* tp_version_tag */
57        NULL,                   /* tp_finalize */
58#if PY_MINOR_VERSION > 7
59        NULL,                   /* tp_vectorcall */
60#endif
61#if PY_MINOR_VERSION == 8
62        0,                          /*tp_print*/
63#endif
64#if PY_MINOR_VERSION >= 12
65        '\0',                   /* unsigned char tp_watched */
66#if PY_MINOR_VERSION >= 13
67        0,                      /* uint16_t tp_versions_used */
68#endif
69#endif
70};

Finally add this to the module (partial code):

 1static struct PyModuleDef cObject = {
 2        PyModuleDef_HEAD_INIT,
 3        "cObject",
 4        module_doc,
 5        -1,
 6        cObject_functions,
 7        NULL,
 8        NULL,
 9        NULL,
10        NULL
11};
12
13PyMODINIT_FUNC
14PyInit_cObject(void) {
15    PyObject *m = NULL;
16
17    /* Create the module and add the functions */
18    m = PyModule_Create(&cObject);
19    if (m == NULL) {
20        goto fail;
21    }
22    /* Add some symbolic constants to the module */
23    if (ErrorObject == NULL) {
24        ErrorObject = PyErr_NewException("cObject.error", NULL, NULL);
25        if (ErrorObject == NULL)
26            goto fail;
27    }
28    Py_INCREF(ErrorObject);
29    if (PyModule_AddObject(m, "error", ErrorObject)) {
30        goto fail;
31    }
32    /* Finalize the type object including setting type of the new type
33     * object; doing it here is required for portability, too. */
34    if (PyType_Ready(&ObjectWithAttributes_Type) < 0) {
35        goto fail;
36    }
37    if (PyModule_AddObject(m, "ObjectWithAttributes",
38                           (PyObject *) &ObjectWithAttributes_Type)) {
39        goto fail;
40    }
41    /* More here ... */
42    return m;
43    fail:
44    Py_XDECREF(m);
45    return NULL;
46}

This can be tested thus, in tests/unit/test_c_object.py:

 1import pytest
 2
 3from cPyExtPatt import cObject
 4
 5def test_ObjectWithAttributes_set_and_get():
 6    obj = cObject.ObjectWithAttributes()
 7    obj.some_attr = 'Some attribute'
 8    assert hasattr(obj, 'some_attr')
 9    assert obj.some_attr == 'Some attribute'
10
11
12def test_ObjectWithAttributes_set_and_del():
13    obj = cObject.ObjectWithAttributes()
14    obj.some_attr = 'Some attribute'
15    assert hasattr(obj, 'some_attr')
16    delattr(obj, 'some_attr')
17    assert not hasattr(obj, 'some_attr')
18    with pytest.raises(AttributeError) as err:
19        obj.some_attr
20    assert err.value.args[0] == "'cObject.ObjectWithAttributes' object has no attribute 'some_attr'"

9.4. Emulating Sequence Types

This section describes how to make an object act like a sequence using tp_as_sequence. See also Sequence Object Structures. This allows your objects to have set and get methods like a list.

As an example here is an extension that can represent a sequence of longs in C with a CPython sequence interface. The code is in src/cpy/Object/cSeqObject.c.

First the class declaration:

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

typedef struct {
    PyObject_HEAD
    long *array_long;
    ssize_t size;
} SequenceLongObject;

Then the equivalent of __new__:

 1static PyObject *
 2SequenceLongObject_new(PyTypeObject *type, PyObject *Py_UNUSED(args),
 3        PyObject *Py_UNUSED(kwds)) {
 4    SequenceLongObject *self;
 5    self = (SequenceLongObject *) 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 the equivalent of __init__ that takes a Python sequence of ints:

 1static int
 2SequenceLongObject_init(SequenceLongObject *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 < self->size; ++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 de-allocation:

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

9.4.1. The Sequence Function Table

The sequence functions are a table of function pointers in the PySequenceMethods table. Here is a summary of the fields, each is described in more detail below:

Sequence Methods

Member

Description

sq_length

Returns the length of the sequence.

sq_concat

Takes two sequences and returns a new third one with the first and second concatenated.

sq_repeat

Returns a new sequence with the old one repeated n times.

sq_item

Returns a new reference to the n’th item in the sequence. Negative indexes are handled appropriately. Used by PySequence_GetItem(). This is a fairly crucial implementation for a sequence as PySequence_Check() detects this to decide if the object is a sequence.

sq_ass_item

Sets the the n’th item in the sequence. If the value is NULL the item is deleted and the sequence concatenated (thus called by PyObject_DelItem()). Negative indexes are handled appropriately. Used by PyObject_SetItem().

sq_ass_contains

Returns non-zero if the sequence contains the given object. Used by PySequence_Contains(). This slot may be left to NULL, in this case PySequence_Contains() simply traverses the sequence until it finds a match.

sq_inplace_concat

Provides in-place concatenation, for example +=. If this slot is NULL then PySequence_Concat() will be used returning a new object.

sq_inplace_repeat

Provides in-place concatenation, for example +=. Returns the existing sequence repeated n times. If this slot is NULL then PySequence_Repeat() will be used returning a new object.

Here are the individual functions, their implementation and the test code.

9.4.2. sq_length

Sequence Methods: sq_length

Member

sq_length

Function type

lenfunc

Function signature

Py_ssize_t (*lenfunc)(PyObject*)

Description

Returns the length of the sequence.

9.4.2.1. Implementation

In src/cpy/Object/cSeqObject.c:

static Py_ssize_t
SequenceLongObject_sq_length(PyObject *self) {
    return ((SequenceLongObject *) self)->size;
}

9.4.2.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

from cPyExtPatt import cSeqObject

def test_SequenceLongObject_len():
    obj = cSeqObject.SequenceLongObject([7, 4, 1, ])
    assert len(obj) == 3

9.4.3. sq_concat

Sequence Methods: sq_concat

Member

sq_concat

Function type

binaryfunc

Function signature

PyObject *(*binaryfunc)(PyObject*, PyObject*)

Description

Takes two sequences and returns a new third one with the first and second concatenated. This is used by the + Python operator and the PySequence_Concat() C API.

9.4.3.1. Implementation

Note the use of forward references for the type checker as we need to check of the second argument is of the correct type. In src/cpy/Object/cSeqObject.c:

 1// Forward references
 2static PyTypeObject SequenceLongObjectType;
 3static int is_sequence_of_long_type(PyObject *op);
 4
 5/** Returns a new SequenceLongObject composed of self + other. */
 6static PyObject *
 7SequenceLongObject_sq_concat(PyObject *self, PyObject *other) {
 8    if (!is_sequence_of_long_type(other)) {
 9        PyErr_Format(
10                PyExc_TypeError,
11                "%s(): argument 1 must have type \"SequenceLongObject\" not %s",
12                Py_TYPE(other)->tp_name
13        );
14        return NULL;
15    }
16    PyObject *ret = SequenceLongObject_new(&SequenceLongObjectType, NULL, NULL);
17    if (!ret) {
18        assert(PyErr_Occurred());
19        return NULL;
20    }
21    /* For convenience. */
22    SequenceLongObject *ret_as_slo = (SequenceLongObject *) ret;
23    ret_as_slo->size = ((SequenceLongObject *) self)->size \
24        + ((SequenceLongObject *) other)->size;
25    ret_as_slo->array_long = malloc(ret_as_slo->size * sizeof(long));
26    if (!ret_as_slo->array_long) {
27        PyErr_Format(
28            PyExc_MemoryError, "%s(): Can not create new object.", __FUNCTION__
29        );
30        Py_DECREF(ret);
31        return NULL;
32    }
33
34    ssize_t i = 0;
35    ssize_t ub = ((SequenceLongObject *) self)->size;
36    while (i < ub) {
37        ret_as_slo->array_long[i] = ((SequenceLongObject *) self)->array_long[i];
38        i++;
39    }
40    ssize_t j = 0;
41    ub = ((SequenceLongObject *) other)->size;
42    while (j < ub) {
43        ret_as_slo->array_long[i] = ((SequenceLongObject *) other)->array_long[j];
44        i++;
45        j++;
46    }
47    return ret;
48}

9.4.3.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

def test_SequenceLongObject_concat():
    obj_a = cSeqObject.SequenceLongObject([7, 4, 1, ])
    obj_b = cSeqObject.SequenceLongObject([70, 40, 100, ])
    assert id(obj_a) != id(obj_b)
    obj = obj_a + obj_b
    assert id(obj) != id(obj_a)
    assert id(obj) != id(obj_b)
    assert len(obj) == 6
    assert list(obj) == [7, 4, 1, ] + [70, 40, 100, ]

9.4.4. sq_repeat

Sequence Methods: sq_repeat

Member

sq_repeat

Function type

ssizeargfunc

Function signature

PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)

Description

Returns a new sequence with the old one repeated the given number of times times. This is used by the * Python operator and the PySequence_Repeat() C API.

9.4.4.1. Implementation

The implementation is fairly straightforward in src/cpy/Object/cSeqObject.c. Note that count can be zero or negative:

 1/** Return a new sequence which contains the old one repeated count times. */
 2static PyObject *
 3SequenceLongObject_sq_repeat(PyObject *self, Py_ssize_t count) {
 4    PyObject *ret = SequenceLongObject_new(&SequenceLongObjectType, NULL, NULL);
 5    if (!ret) {
 6        assert(PyErr_Occurred());
 7        return NULL;
 8    }
 9    assert(ret != self);
10    if (((SequenceLongObject *) self)->size > 0 && count > 0) {
11        /* For convenience. */
12        SequenceLongObject *self_as_slo = (SequenceLongObject *) self;
13        SequenceLongObject *ret_as_slo = (SequenceLongObject *) ret;
14        ret_as_slo->size = self_as_slo->size * count;
15        assert(ret_as_slo->size > 0);
16        ret_as_slo->array_long = malloc(ret_as_slo->size * sizeof(long));
17        if (!ret_as_slo->array_long) {
18            PyErr_Format(
19                PyExc_MemoryError, "%s(): Can not create new object.", __FUNCTION__
20            );
21            Py_DECREF(ret);
22            return NULL;
23        }
24        Py_ssize_t ret_index = 0;
25        for (Py_ssize_t i = 0; i < count; ++i) {
26            for (Py_ssize_t j = 0; j < self_as_slo->size; ++j) {
27                ret_as_slo->array_long[ret_index] = self_as_slo->array_long[j];
28                ++ret_index;
29            }
30        }
31    } else {
32        /* Empty sequence. */
33    }
34    return ret;
35}

9.4.4.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

 1@pytest.mark.parametrize(
 2    'initial_sequence, count, expected',
 3    (
 4        ([], 1, [],),
 5        ([7, 4, 1, ], 0, [],),
 6        ([7, 4, 1, ], -1, [],),
 7        ([7, 4, 1, ], 1, [7, 4, 1, ],),
 8        ([7, 4, 1, ], 2, [7, 4, 1, 7, 4, 1, ],),
 9        ([7, 4, 1, ], 3, [7, 4, 1, 7, 4, 1, 7, 4, 1, ],),
10    )
11)
12def test_SequenceLongObject_repeat(initial_sequence, count, expected):
13    obj_a = cSeqObject.SequenceLongObject(initial_sequence)
14    obj = obj_a * count
15    print()
16    assert id(obj_a) != id(obj)
17    assert list(obj) == expected
18    assert list(obj) == (list(obj_a) * count)

9.4.5. sq_item

sq_item gives read access to an indexed member.

Sequence Methods: sq_item

Member

sq_item

Function type

ssizeargfunc

Function signature

PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)

Description

Returns a new reference to the n’th item in the sequence. Negative indexes are handled appropriately. Used by PySequence_GetItem(). This is a fairly crucial implementation for a sequence as PySequence_Check() detects this to decide if the object is a sequence.

9.4.5.1. Implementation

In src/cpy/Object/cSeqObject.c:

 1/** Returns a new reference to an indexed item in a sequence. */
 2static PyObject *
 3SequenceLongObject_sq_item(PyObject *self, Py_ssize_t index) {
 4    Py_ssize_t my_index = index;
 5    if (my_index < 0) {
 6        my_index += SequenceLongObject_sq_length(self);
 7    }
 8    // Corner case example: len(self) == 0 and index < 0
 9    if (my_index < 0 || my_index >= SequenceLongObject_sq_length(self)) {
10        PyErr_Format(
11                PyExc_IndexError,
12                "Index %ld is out of range for length %ld",
13                index,
14                SequenceLongObject_sq_length(self)
15        );
16        return NULL;
17    }
18    return PyLong_FromLong(((SequenceLongObject *) self)->array_long[my_index]);
19}

9.4.5.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, expected',
 5    (
 6            ([7, 4, 1, ], 0, 7,),
 7            ([7, 4, 1, ], 1, 4,),
 8            ([7, 4, 1, ], 2, 1,),
 9            ([7, 4, 1, ], -1, 1,),
10            ([7, 4, 1, ], -2, 4,),
11            ([7, 4, 1, ], -3, 7,),
12    )
13)
14def test_SequenceLongObject_item(initial_sequence, index, expected):
15    obj = cSeqObject.SequenceLongObject(initial_sequence)
16    assert obj[index] == expected

And failure modes:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, expected',
 5    (
 6            ([], 0, 'Index 0 is out of range for length 0',),
 7            ([], -1, 'Index -1 is out of range for length 0',),
 8            ([1, ], 2, 'Index 2 is out of range for length 1',),
 9    )
10)
11def test_SequenceLongObject_item_raises(initial_sequence, index, expected):
12    obj = cSeqObject.SequenceLongObject(initial_sequence)
13    with pytest.raises(IndexError) as err:
14        obj[index]
15    assert err.value.args[0] == expected

9.4.6. sq_ass_item

sq_ass_item gives write and delete access to an indexed member.

Sequence Methods: sq_ass_item

Member

sq_ass_item

Function type

ssizeobjargproc

Function signature

int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)

Description

Sets the the n’th item in the sequence. Returns 0 on success, -1 on failure. If the value is NULL the item is deleted and the sequence concatenated (thus called by PyObject_DelItem()). Negative indexes are handled appropriately. Used by PyObject_SetItem().

9.4.6.1. Implementation

Warning

There is an undocumented feature when using sq_ass_item from PyObject_SetItem() and PyObject_DelItem() when using negative indexes and when the index is out of range.

In that case, before the sq_ass_item function is called the index will have had the sequence length added to it.

For example if the sequence length is 3 and the given index is -4 then the index that the sq_ass_item function receives is -1. If the given index is -5 then the index that the sq_ass_item function receives is -2.

Thus the slightly odd code below to fix this problem. Failing to do this will mean out of range errors will not be detected by the sq_ass_item function and any error message will be wrong.

In src/cpy/Object/cSeqObject.c:

 1static int
 2SequenceLongObject_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) {
 3    /* See warning above. */
 4    if (index < 0) {
 5        index -= SequenceLongObject_sq_length(self);
 6    }
 7
 8    Py_ssize_t my_index = index;
 9    if (my_index < 0) {
10        my_index += SequenceLongObject_sq_length(self);
11    }
12    // Corner case example: len(self) == 0 and index < 0
13    if (my_index < 0 || my_index >= SequenceLongObject_sq_length(self)) {
14        PyErr_Format(
15                PyExc_IndexError,
16                "Index %ld is out of range for length %ld",
17                index,
18                SequenceLongObject_sq_length(self)
19        );
20        return -1;
21    }
22    if (value != NULL) {
23        /* Just set the value. */
24        if (!PyLong_Check(value)) {
25            PyErr_Format(
26                    PyExc_TypeError,
27                    "sq_ass_item value needs to be an int, not type %s",
28                    Py_TYPE(value)->tp_name
29            );
30            return -1;
31        }
32        ((SequenceLongObject *) self)->array_long[my_index] = PyLong_AsLong(value);
33    } else {
34        /* Delete the value. */
35        /* For convenience. */
36        SequenceLongObject *self_as_slo = (SequenceLongObject *) self;
37        /* Special case: deleting the only item in the array. */
38        if (self_as_slo->size == 1) {
39            free(self_as_slo->array_long);
40            self_as_slo->array_long = NULL;
41            self_as_slo->size = 0;
42        } else {
43            /* Delete the value and re-compose the array. */
44            long *new_array = malloc((self_as_slo->size - 1) * sizeof(long));
45            if (!new_array) {
46                PyErr_Format(
47                        PyExc_MemoryError,
48                        "sq_ass_item can not allocate new array. %s#%d",
49                        __FILE__, __LINE__
50                );
51                return -1;
52            }
53            /* Copy up to the index. */
54            Py_ssize_t index_new_array = 0;
55            for (Py_ssize_t i = 0; i < my_index; ++i, ++index_new_array) {
56                new_array[index_new_array] = self_as_slo->array_long[i];
57            }
58            /* Copy past the index. */
59            for (
60                Py_ssize_t i = my_index + 1;
61                i < self_as_slo->size;
62                ++i, ++index_new_array) {
63                new_array[index_new_array] = self_as_slo->array_long[i];
64            }
65
66            free(self_as_slo->array_long);
67            self_as_slo->array_long = new_array;
68            --self_as_slo->size;
69        }
70    }
71    return 0;
72}

9.4.6.2. Tests

Tests are in tests/unit/test_c_seqobject.py which includes failure modes. First setting a value:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, value, expected',
 5    (
 6        ([7, 4, 1, ], 0, 14, [14, 4, 1, ],),
 7        ([7, 4, 1, ], -1, 14, [7, 4, 14, ],),
 8        ([7, 4, 1, ], -2, 14, [7, 14, 1, ],),
 9        ([7, 4, 1, ], -3, 14, [14, 4, 1, ],),
10    )
11)
12def test_SequenceLongObject_setitem(initial_sequence, index, value, expected):
13    obj = cSeqObject.SequenceLongObject(initial_sequence)
14    obj[index] = value
15    assert list(obj) == expected

Setting a value with an out of range index:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, expected',
 5    (
 6        ([7, 4, 1, ], 3, 'Index 3 is out of range for length 3',),
 7        ([7, 4, 1, ], -4, 'Index -4 is out of range for length 3',),
 8    )
 9)
10def test_SequenceLongObject_setitem_raises(initial_sequence, index, expected):
11    obj = cSeqObject.SequenceLongObject(initial_sequence)
12    with pytest.raises(IndexError) as err:
13        obj[index] = 100
14    assert err.value.args[0] == expected

Deleting a value:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, expected',
 5    (
 6        ([7, ], 0, [],),
 7        ([7, ], -1, [],),
 8        ([7, 4, 1, ], 1, [7, 1, ],),
 9        ([7, 4, ], 0, [4, ],),
10        ([7, 4, 1, ], -1, [7, 4, ],),
11        ([7, 4, 1, ], -2, [7, 1, ],),
12        ([7, 4, 1, ], -3, [4, 1, ],),
13    )
14)
15def test_SequenceLongObject_delitem(initial_sequence, index, expected):
16    obj = cSeqObject.SequenceLongObject(initial_sequence)
17    del obj[index]
18    assert list(obj) == expected

Deleting a value with an out of range index:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, index, expected',
 5    (
 6        ([], 0, 'Index 0 is out of range for length 0',),
 7        ([], -1, 'Index -1 is out of range for length 0',),
 8        ([7, ], 1, 'Index 1 is out of range for length 1',),
 9        ([7, ], -3, 'Index -3 is out of range for length 1',),
10    )
11)
12def test_SequenceLongObject_delitem_raises(initial_sequence, index, expected):
13    obj = cSeqObject.SequenceLongObject(initial_sequence)
14    with pytest.raises(IndexError) as err:
15        del obj[index]
16    assert err.value.args[0] == expected

9.4.7. sq_ass_contains

Sequence Methods: sq_ass_contains

Member

sq_ass_contains

Function type

objobjproc

Function signature

int (*objobjproc)(PyObject*, PyObject*)

Description

Returns non-zero if the sequence contains the given object. If an item in o is equal to value, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression value in o. Used by PySequence_Contains(). This slot may be left to NULL, in this case PySequence_Contains() simply traverses the sequence until it finds a match.

9.4.7.1. Implementation

In src/cpy/Object/cSeqObject.c:

 1/** If an item in self is equal to value, return 1, otherwise return 0.
 2 * On error, return -1. */
 3static int
 4SequenceLongObject_sq_contains(PyObject *self, PyObject *value) {
 5    fprintf(
 6            stdout, "%s()#%d: self=%p value=%p\n",
 7            __FUNCTION__, __LINE__, (void *) self, (void *) value
 8    );
 9    if (!PyLong_Check(value)) {
10        /* Alternates: Could raise TypeError or return -1.
11         * Here we act benignly! */
12        return 0;
13    }
14    long c_value = PyLong_AsLong(value);
15    /* For convenience. */
16    SequenceLongObject *self_as_slo = (SequenceLongObject *) self;
17    for (Py_ssize_t i = 0; i < SequenceLongObject_sq_length(self); ++i) {
18        if (self_as_slo->array_long[i] == c_value) {
19            return 1;
20        }
21    }
22    return 0;
23}

Note

Whilst SequenceLongObject_sq_contains() returns 0 or 1 however Python code such as value in obj converts this to False and True respectively

9.4.7.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, value, expected',
 5    (
 6        ([7, ], 0, False,),
 7        ([7, ], 7, True,),
 8        ([1, 4, 7, ], 7, True,),
 9    )
10)
11def test_SequenceLongObject_contains(initial_sequence, value, expected):
12    obj = cSeqObject.SequenceLongObject(initial_sequence)
13    result = value in obj
14    assert result == expected

9.4.8. sq_inplace_concat

Sequence Methods: sq_inplace_concat

Member

sq_inplace_concat

Function type

binaryfunc

Function signature

PyObject *(*binaryfunc)(PyObject*, PyObject*)

Description

Provides in-place concatenation, for example +=. If this slot is NULL then PySequence_InPlaceConcat() will use PySequence_Concat().

9.4.8.1. Implementation

If sq_concat is implemented then this need not be implemented In src/cpy/Object/cSeqObject.c this is not implemented to show this mechanism at work.

9.4.8.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

from cPyExtPatt import cSeqObject

def test_SequenceLongObject_concat_inplace():
    obj_a = cSeqObject.SequenceLongObject([7, 4, 1, ])
    obj_b = cSeqObject.SequenceLongObject([70, 40, 100, ])
    assert id(obj_a) != id(obj_b)
    obj_a += obj_b
    assert len(obj_a) == 6
    assert list(obj_a) == [7, 4, 1, ] + [70, 40, 100, ]

9.4.9. sq_inplace_repeat

Sequence Methods: sq_inplace_repeat

Member

sq_inplace_repeat

Function type

ssizeargfunc

Function signature

PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)

Description

Provides in-place concatenation, for example +=. Returns the existing sequence repeated n times. If this slot is NULL then PySequence_Repeat() will be used returning a new object.

9.4.9.1. Implementation

If sq_repeat is implemented then this need not be implemented In src/cpy/Object/cSeqObject.c this is not implemented to show this mechanism at work.

9.4.9.2. Tests

Tests are in tests/unit/test_c_seqobject.py:

 1from cPyExtPatt import cSeqObject
 2
 3@pytest.mark.parametrize(
 4    'initial_sequence, count, expected',
 5    (
 6        ([], 1, [],),
 7        ([7, 4, 1, ], 0, [],),
 8        ([7, 4, 1, ], -1, [],),
 9        ([7, 4, 1, ], 1, [7, 4, 1, ],),
10        ([7, 4, 1, ], 2, [7, 4, 1, 7, 4, 1, ],),
11        ([7, 4, 1, ], 3, [7, 4, 1, 7, 4, 1, 7, 4, 1, ],),
12    )
13)
14def test_SequenceLongObject_repeat_inplace(initial_sequence, count, expected):
15    obj = cSeqObject.SequenceLongObject(initial_sequence)
16    obj *= count
17    assert list(obj) == expected
18    assert list(obj) == (initial_sequence * count)

9.4.10. The Function Table

All these functions are gathered together in a PySequenceMethods table:

 1static PySequenceMethods SequenceLongObject_sequence_methods = {
 2        .sq_length = (lenfunc)SequenceLongObject_sq_length,
 3        .sq_concat = (binaryfunc)SequenceLongObject_sq_concat,
 4        .sq_repeat = (ssizeargfunc)SequenceLongObject_sq_repeat,
 5        .sq_item = (ssizeargfunc)SequenceLongObject_sq_item,
 6        .sq_ass_item = (ssizeobjargproc)SequenceLongObject_sq_ass_item,
 7        .sq_contains = (objobjproc)SequenceLongObject_sq_contains,
 8        .sq_inplace_concat = (binaryfunc)NULL,      // Not implemented. See above.
 9        .sq_inplace_repeat = (ssizeargfunc)NULL,    // Not implemented. See above.
10};

And the SequenceLongObjectType type is declared with the tp_as_sequence field referring to this table:

 1static PyTypeObject SequenceLongObjectType = {
 2        PyVarObject_HEAD_INIT(NULL, 0)
 3        .tp_name = "SequenceLongObject",
 4        .tp_basicsize = sizeof(SequenceLongObject),
 5        .tp_itemsize = 0,
 6        .tp_dealloc = (destructor) SequenceLongObject_dealloc,
 7        .tp_as_sequence = &SequenceLongObject_sequence_methods,
 8        .tp_str = (reprfunc) SequenceLongObject___str__,
 9        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
10        .tp_doc = "Sequence of long integers.",
11        .tp_methods = SequenceLongObject_methods,
12        .tp_init = (initproc) SequenceLongObject_init,
13        .tp_new = SequenceLongObject_new,
14};

9.4.11. Module Initialisation

This is as usual:

 1static PyModuleDef sequence_object_cmodule = {
 2    PyModuleDef_HEAD_INIT,
 3    .m_name = "cSeqObject",
 4    .m_doc = (
 5        "Example module that creates an extension type with sequence methods"
 6    ),
 7    .m_size = -1,
 8    .m_methods = cIterator_methods,
 9};
10
11PyMODINIT_FUNC
12PyInit_cSeqObject(void) {
13    PyObject *m;
14    m = PyModule_Create(&sequence_object_cmodule);
15    if (m == NULL) {
16        return NULL;
17    }
18
19    if (PyType_Ready(&SequenceLongObjectType) < 0) {
20        Py_DECREF(m);
21        return NULL;
22    }
23    Py_INCREF(&SequenceLongObjectType);
24    if (PyModule_AddObject(
25            m,
26            "SequenceLongObject",
27            (PyObject *) &SequenceLongObjectType) < 0
28            ) {
29        Py_DECREF(&SequenceLongObjectType);
30        Py_DECREF(m);
31        return NULL;
32    }
33    return m;
34}

9.5. TODOs:

Todo

“Creating New Types”: Add a section on making an object act like a number using tp_as_number. See also Number Object Structures

Todo

“Creating New Types”: Add a section on making an object act like a mapping object using tp_as_mapping. See also Mapping Object Structures

NOTE: This is rarely used in the Python stdlib, really only for dictionaries.