14. Capsules¶
Usually C extension code is used solely by the extension itself, for that reason all functions are declared static
however there are cases where the C extension code is useful to another C extension.
When modules are used as shared libraries the symbols in one extension might not be visible to another extension.
Capsules are a means by which this can be achieved by passing C pointers from one extension module to another.
14.1. A Simple Example¶
This takes the example given in the Python documentation and makes it complete.
The code is in src/cpy/Capsules/spam*.
14.1.1. Basic Extension¶
Here is the basic example of an Extension that can make a system call.
The code is in src/cpy/Capsules/spam.c.
1#define PY_SSIZE_T_CLEAN
2#include <Python.h>
3
4static PyObject *
5spam_system(PyObject *Py_UNUSED(self), PyObject *args) {
6 const char *command;
7 int sts;
8
9 if (!PyArg_ParseTuple(args, "s", &command))
10 return NULL;
11 sts = system(command);
12 return PyLong_FromLong(sts);
13}
14
15static PyMethodDef SpamMethods[] = {
16 /* ... */
17 {"system", spam_system, METH_VARARGS,
18 "Execute a shell command."},
19 /* ... */
20 {NULL, NULL, 0, NULL} /* Sentinel */
21};
22
23static struct PyModuleDef spammodule = {
24 PyModuleDef_HEAD_INIT,
25 "spam", /* name of module */
26 PyDoc_STR("Documentation for the spam module"),
27 -1, /* size of per-interpreter state of the module,
28 or -1 if the module keeps state in global variables. */
29 SpamMethods,
30 NULL, NULL, NULL, NULL,
31};
32
33PyMODINIT_FUNC
34PyInit_spam(void) {
35 return PyModule_Create(&spammodule);
36}
This would be built with this entry in setup.py:
Extension(f"{PACKAGE_NAME}.Capsules.spam", sources=['src/cpy/Capsules/spam.c',],
include_dirs=['/usr/local/include', ],
library_dirs=[os.getcwd(), ],
extra_compile_args=extra_compile_args_c,
language='c',
),
This can be tested with the code in tests/unit/test_c_capsules.py:
from cPyExtPatt.Capsules import spam
def test_spam():
result = spam.system("ls -l")
assert result == 0
14.1.2. An Exportable Extension¶
To make a version that exports its API in a Capsule we will make some changes:
Introduce a function
PySpam_Systemthat actually does the system call. We will export this.Introduce a header file
src/cpy/Capsules/spam_capsule.hthat contains the exports.Introduce a macro
SPAM_CAPSULEthat controls whether we are exporting or importing the API.Change the module initialisation to initialise the API.
The header file in src/cpy/Capsules/spam_capsule.h looks like this:
1#ifndef Py_SPAM_CAPSULE_H
2#define Py_SPAM_CAPSULE_H
3#ifdef __cplusplus
4extern "C" {
5#endif
6
7#include <Python.h>
8
9/* Header file for spammodule */
10
11/* C API functions */
12#define PySpam_System_NUM 0
13#define PySpam_System_RETURN int
14#define PySpam_System_PROTO (const char *command)
15
16/* Total number of C API pointers */
17#define PySpam_API_pointers 1
18
19#ifdef SPAM_CAPSULE
20
21/* This section is used when compiling spam_capsule.c */
22static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
23
24#else
25/* This section is used in modules that use spam_capsule's API */
26static void **PySpam_API;
27
28#define PySpam_System \
29 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
30
31/* Return -1 on error, 0 on success.
32 * PyCapsule_Import will set an exception if there's an error.
33 */
34static int
35import_spam_capsule(void) {
36 PySpam_API = (void **)PyCapsule_Import("cPyExtPatt.Capsules.spam_capsule._C_API", 0);
37 return (PySpam_API != NULL) ? 0 : -1;
38}
39#endif
40#ifdef __cplusplus
41}
42#endif
43#endif /* !defined(Py_SPAM_CAPSULE_H) */
The full code is in src/cpy/Capsules/spam_capsule.c:
1// Implements: https://docs.python.org/3/extending/extending.html#extending-simpleexample
2// as a capsule: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
3// Includes specific exception.
4// Lightly edited.
5
6#define PY_SSIZE_T_CLEAN
7
8#include <Python.h>
9
10#define SPAM_CAPSULE
11
12#include "spam_capsule.h"
13
14static int
15PySpam_System(const char *command) {
16 return system(command);
17}
18
19static PyObject *
20spam_system(PyObject *Py_UNUSED(self), PyObject *args) {
21 const char *command;
22 int sts;
23
24 if (!PyArg_ParseTuple(args, "s", &command))
25 return NULL;
26 sts = PySpam_System(command);
27 return PyLong_FromLong(sts);
28}
29
30static PyMethodDef SpamMethods[] = {
31 /* ... */
32 {"system", spam_system, METH_VARARGS,
33 "Execute a shell command."},
34 /* ... */
35 {NULL, NULL, 0, NULL} /* Sentinel */
36};
37
38static struct PyModuleDef spammodule = {
39 PyModuleDef_HEAD_INIT,
40 "spam_capsule", /* name of module */
41 PyDoc_STR("Documentation for the spam module"),
42 -1, /* size of per-interpreter state of the module,
43 or -1 if the module keeps state in global variables. */
44 SpamMethods,
45 NULL, NULL, NULL, NULL,
46};
47
48PyMODINIT_FUNC
49PyInit_spam_capsule(void) {
50 PyObject *m;
51 static void *PySpam_API[PySpam_API_pointers];
52 PyObject *c_api_object;
53
54 m = PyModule_Create(&spammodule);
55 if (m == NULL)
56 return NULL;
57
58 /* Initialize the C API pointer array */
59 PySpam_API[PySpam_System_NUM] = (void *) PySpam_System;
60
61 /* Create a Capsule containing the API pointer array's address */
62 c_api_object = PyCapsule_New((void *) PySpam_API, "cPyExtPatt.Capsules.spam_capsule._C_API", NULL);
63
64 if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) {
65 Py_XDECREF(c_api_object);
66 Py_DECREF(m);
67 return NULL;
68 }
69 return m;
70}
This can be built by adding this Extension to setup.py:
Extension(f"{PACKAGE_NAME}.Capsules.spam_capsule",
sources=['src/cpy/Capsules/spam_capsule.c',],
include_dirs=['/usr/local/include', 'src/cpy/Capsules',],
library_dirs=[os.getcwd(), ],
extra_compile_args=extra_compile_args_c,
language='c',
),
This can be tested with the code in tests/unit/test_c_capsules.py:
from cPyExtPatt.Capsules import spam_capsule
def test_spam_capsule():
result = spam_capsule.system("ls -l")
assert result == 0
14.1.3. A Client Extension¶
This can now be used by another extension, say spam_client in src/cpy/Capsules/spam_client.c.
Note the use of:
#include "spam_capsule.h"The call to the imported function
PySpam_System.Calling
import_spam_capsule()in the module initialisation.
Here is the complete C code:
1// Implements: https://docs.python.org/3/extending/extending.html#extending-simpleexample
2// but using a capsule exported by spam_capsule.h/.c
3// Excludes specific exception.
4// Lightly edited.
5
6#define PY_SSIZE_T_CLEAN
7
8#include <Python.h>
9#include "spam_capsule.h"
10
11static PyObject *
12spam_system(PyObject *Py_UNUSED(self), PyObject *args) {
13 const char *command;
14 int sts;
15
16 if (!PyArg_ParseTuple(args, "s", &command))
17 return NULL;
18 sts = PySpam_System(command);
19 return PyLong_FromLong(sts);
20}
21
22static PyMethodDef SpamMethods[] = {
23 /* ... */
24 {"system", spam_system, METH_VARARGS,
25 "Execute a shell command."},
26 /* ... */
27 {NULL, NULL, 0, NULL} /* Sentinel */
28};
29
30static struct PyModuleDef spam_clientmodule = {
31 PyModuleDef_HEAD_INIT,
32 "spam_client", /* name of module */
33 PyDoc_STR("Documentation for the spam module"),
34 -1, /* size of per-interpreter state of the module,
35 or -1 if the module keeps state in global variables. */
36 SpamMethods,
37 NULL, NULL, NULL, NULL,
38};
39
40PyMODINIT_FUNC
41PyInit_spam_client(void) {
42 PyObject *m;
43
44 m = PyModule_Create(&spam_clientmodule);
45 if (m == NULL)
46 return NULL;
47 if (import_spam_capsule() < 0)
48 return NULL;
49 /* additional initialization can happen here */
50 return m;
51}
This can be built by adding this Extension to setup.py:
Extension(f"{PACKAGE_NAME}.Capsules.spam_client",
sources=['src/cpy/Capsules/spam_client.c',],
include_dirs=['/usr/local/include', 'src/cpy/Capsules',],
library_dirs=[os.getcwd(), ],
extra_compile_args=extra_compile_args_c,
language='c',
),
This can be tested with the code in tests/unit/test_c_capsules.py:
from cPyExtPatt.Capsules import spam_client
def test_spam_client():
result = spam_client.system("ls -l")
assert result == 0
14.2. Using an Existing Capsule¶
Here is an example of using an existing Capsule, the datetime C API.
In this case we want to create a subclass of the datetime.datetime object that always has a time zone i.e. no
naive datetimes.
Here is the C Extension code to create a datetimetz module and a datetimetz.datetimetz object.
This code is lightly edited for clarity and works with Python 3.10+ (using the modern API).
The actual code is in src/cpy/Capsules/datetimetz.c (which works with the Python 3.9 API as well)
and the tests are in tests/unit/test_c_capsules.py.
14.2.1. Writing the Code for the Object¶
Firstly the declaration of the timezone aware datetime, it just inherits from datetime.datetime :
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "datetime.h"
typedef struct {
PyDateTime_DateTime datetime;
} DateTimeTZ;
Then create a function that sets an error if the DateTimeTZ lacks a tzinfo
This will be used in a couple of places.
1/* This function sets an error if a tzinfo is not set and returns NULL.
2 * In practice this would use Python version specific calls.
3 * For simplicity this uses Python 3.10+ code.
4 */
5static DateTimeTZ *
6raise_if_no_tzinfo(DateTimeTZ *self) {
7 if (!_PyDateTime_HAS_TZINFO(&self->datetime)) {
8 PyErr_SetString(PyExc_TypeError, "No time zone provided.");
9 Py_DECREF(self);
10 self = NULL;
11 }
12 return self;
13}
Now the code for creating a new instance:
1static PyObject *
2DateTimeTZ_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
3 DateTimeTZ *self = (DateTimeTZ *) PyDateTimeAPI->DateTimeType->tp_new(
4 type, args, kwds
5 );
6 if (self) {
7 self = raise_if_no_tzinfo(self);
8 }
9 return (PyObject *) self;
10}
So far a new datetimetz object must be created with a tzinfo but the datetime.datetime has an API
replace() that creates a new datetime with different properties, including tzinfo.
We need to guard against the user trying to change the timezone to None.
To do this we call the super class function and then check, and raise, if a tzinfo is absent.
This uses the utility function that call Python’s super() function.
That code is in src/cpy/Util/py_call_super.h and src/cpy/Util/py_call_super.c:
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;
}
Finally the module code:
1static PyMethodDef DateTimeTZ_methods[] = {
2 {
3 "replace",
4 (PyCFunction) DateTimeTZ_replace,
5 METH_VARARGS | METH_KEYWORDS,
6 PyDoc_STR("Return datetime with new specified fields.")
7 },
8 {NULL, NULL, 0, NULL} /* Sentinel */
9};
10
11static PyTypeObject DatetimeTZType = {
12 PyVarObject_HEAD_INIT(NULL, 0)
13 .tp_name = "datetimetz.datetimetz",
14 .tp_doc = "A datetime that requires a time zone.",
15 .tp_basicsize = sizeof(DateTimeTZ),
16 .tp_itemsize = 0,
17 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
18 .tp_new = DateTimeTZ_new,
19 .tp_methods = DateTimeTZ_methods,
20};
21
22static PyModuleDef datetimetzmodule = {
23 PyModuleDef_HEAD_INIT,
24 .m_name = "datetimetz",
25 .m_doc = (
26 "Module that contains a datetimetz,"
27 "a datetime.datetime with a mandatory time zone."
28 ),
29 .m_size = -1,
30};
Initialise the module, this is when we use the existing capsule:
1PyMODINIT_FUNC
2PyInit_datetimetz(void) {
3 PyObject *m = PyModule_Create(&datetimetzmodule);
4 if (m == NULL) {
5 return NULL;
6 }
7 // datetime.datetime_CAPI
8 PyDateTime_IMPORT;
9 if (!PyDateTimeAPI) {
10 Py_DECREF(m);
11 return NULL;
12 }
13 // Set inheritance.
14 DatetimeTZType.tp_base = PyDateTimeAPI->DateTimeType;
15 if (PyType_Ready(&DatetimeTZType) < 0) {
16 Py_DECREF(m);
17 return NULL;
18 }
19 Py_INCREF(&DatetimeTZType);
20 PyModule_AddObject(m, "datetimetz", (PyObject *) &DatetimeTZType);
21 /* additional initialization can happen here */
22 return m;
23}
The extension is created with this in setup.py:
1Extension(f"{PACKAGE_NAME}.Capsules.datetimetz",
2 sources=[
3 'src/cpy/Capsules/datetimetz.c',
4 'src/cpy/Util/py_call_super.c',
5 ],
6 include_dirs=[
7 '/usr/local/include',
8 'src/cpy/Capsules',
9 'src/cpy/Util',
10 ],
11 library_dirs=[os.getcwd(), ],
12 extra_compile_args=extra_compile_args_c,
13 language='c',
14 ),
Extensive tests are in tests/unit/test_c_capsules.py.
14.2.2. Building¶
Running python setup.py develop will build the extension(s) and then dtatetimetz can be imported:
from cPyExtPatt.Capsules import datetimetz
14.2.3. Testing¶
All the ests are in tests/unit/test_c_capsules.py, but here is a relevant selection.
All depend on:
import datetime
import zoneinfo
import pytest
from cPyExtPatt.Capsules import datetimetz
A check on the __mro__:
def test_datetimetz_datetimetz_mro():
mro = datetimetz.datetimetz.__mro__
assert [str(v) for v in mro] == [
"<class 'datetimetz.datetimetz'>",
"<class 'datetime.datetime'>",
"<class 'datetime.date'>",
"<class 'object'>",
]
A check on construction, first with a timezone, then without:
1@pytest.mark.parametrize(
2 'args, kwargs, expected',
3 (
4 (
5 (2024, 7, 15, 10, 21, 14),
6 {'tzinfo': zoneinfo.ZoneInfo('Europe/London')},
7 '2024-07-15 10:21:14+01:00',
8 ),
9 )
10)
11def test_datetimetz_datetimetz_str(args, kwargs, expected):
12 d = datetimetz.datetimetz(*args, **kwargs)
13 assert str(d) == expected
14
15
16@pytest.mark.parametrize(
17 'args, kwargs, expected',
18 (
19 (
20 (2024, 7, 15, 10, 21, 14),
21 {},
22 'No time zone provided.',
23 ),
24 (
25 (2024, 7, 15, 10, 21, 14),
26 {'tzinfo': None, },
27 'No time zone provided.',
28 ),
29 )
30)
31def test_datetimetz_datetimetz_raises(args, kwargs, expected):
32 with pytest.raises(TypeError) as err:
33 d = datetimetz.datetimetz(*args, **kwargs)
34 assert err.value.args[0] == expected
Check the repr().
Note how this uses inheritance correctly whilst getting the type right:
1@pytest.mark.parametrize(
2 'args, kwargs, expected',
3 (
4 (
5 (2024, 7, 15, 10, 21, 14),
6 {'tzinfo': zoneinfo.ZoneInfo('Europe/London')},
7 (
8 "datetimetz.datetimetz(2024, 7, 15, 10, 21, 14,"
9 " tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))"
10 ),
11 ),
12 )
13)
14def test_datetimetz_datetimetz_repr(args, kwargs, expected):
15 d = datetimetz.datetimetz(*args, **kwargs)
16 assert repr(d) == expected
Here is a test for setting the tzinfo directly.
The error is handled correctly by the superclass.
def test_datetimetz_datetimetz_set_tzinfo_raises():
d = datetimetz.datetimetz(
2024, 7, 15, 10, 21, 14,
tzinfo=zoneinfo.ZoneInfo('Europe/London')
)
with pytest.raises(AttributeError) as err:
d.tzinfo = None
assert err.value.args[0] == "attribute 'tzinfo' of 'datetime.datetime' objects is not writable"
Check that .replace() works as expected with tzinfo:
def test_datetimetz_datetimetz_replace_raises_tzinfo():
d = datetimetz.datetimetz(
2024, 7, 15, 10, 21, 14,
tzinfo=zoneinfo.ZoneInfo('Europe/London')
)
with pytest.raises(TypeError) as err:
d.replace(tzinfo=None)
assert err.value.args[0] == 'No time zone provided.'
Some equality tests.
We want to fail when comparing our datetimetz with a naive datatime object.
1def test_datetimetz_datetimetz_equal():
2 d_tz = datetimetz.datetimetz(
3 2024, 7, 15, 10, 21, 14,
4 tzinfo=zoneinfo.ZoneInfo('Europe/London'))
5 d = datetime.datetime(
6 2024, 7, 15, 10, 21, 14,
7 tzinfo=zoneinfo.ZoneInfo('Europe/London')
8 )
9 assert d_tz == d
10
11
12def test_datetime_datetime_equal_naive():
13 d = datetime.datetime(
14 2024, 7, 15, 10, 21, 14,
15 tzinfo=zoneinfo.ZoneInfo('Europe/London')
16 )
17 d_no_tz = datetime.datetime(2024, 7, 15, 10, 21, 14)
18 assert d_no_tz != d
Some datetime subtraction tests that show our datetimetz inter-operates correctly with itself and a datetime
object.
1@pytest.mark.parametrize(
2 'd_tz, d, expected',
3 (
4 (
5 datetimetz.datetimetz(
6 2024, 7, 15, 10, 21, 14,
7 tzinfo=zoneinfo.ZoneInfo('Europe/London')
8 ),
9 datetime.datetime(
10 2024, 7, 15, 10, 21, 14,
11 tzinfo=zoneinfo.ZoneInfo('Europe/London')
12 ),
13 datetime.timedelta(0),
14 ),
15 (
16 datetimetz.datetimetz(
17 2024, 7, 15, 10, 21, 14,
18 tzinfo=zoneinfo.ZoneInfo('Europe/London')
19 ),
20 datetime.datetime(
21 2024, 7, 15, 10, 21, 14,
22 tzinfo=zoneinfo.ZoneInfo('America/New_York')
23 ),
24 datetime.timedelta(seconds=-5 * 60 * 60),
25 ),
26 (
27 datetimetz.datetimetz(
28 2024, 7, 15, 10, 21, 14,
29 tzinfo=zoneinfo.ZoneInfo('America/New_York')
30 ),
31 datetime.datetime(
32 2024, 7, 15, 10, 21, 14,
33 tzinfo=zoneinfo.ZoneInfo('Europe/London')
34 ),
35 datetime.timedelta(seconds=5 * 60 * 60),
36 ),
37 )
38)
39def test_datetimetz_datetimetz_subtract(d_tz, d, expected):
40 assert (d_tz - d) == expected
41
42
43@pytest.mark.parametrize(
44 'd_tz, d, expected',
45 (
46 (
47 datetimetz.datetimetz(
48 2024, 7, 15, 10, 21, 14,
49 tzinfo=zoneinfo.ZoneInfo('Europe/London')
50 ),
51 datetime.datetime(2024, 7, 15, 10, 21, 14),
52 '',
53 ),
54 )
55)
56def test_datetimetz_datetimetz_subtract_raises(d_tz, d, expected):
57 with pytest.raises(TypeError) as err:
58 d_tz - d
59 assert err.value.args[0] == "can't subtract offset-naive and offset-aware datetimes"