Writing a C Extension Module for Python by Hand
This article explains how a CPython extension module is written in C, defined with multi-phase initialization, built with setuptools and used from Python, and when other tools are preferable.
Many of the most used Python libraries contain modules written in C, which the interpreter imports exactly as it imports a .py file. The present article examines how such an extension module is written by hand against the C API of CPython: the structure of the C source, the module definition that the interpreter reads at import time, the build with setuptools and the use of the result from Python. It also measures where the speed of C actually appears, corrects several practices that were common in older tutorials but no longer work or no longer suffice in Python 3.14, and compares the C API with the tools that the official documentation recommends considering first. Placing a small piece of compiled code exactly where the interpreter spends its time, behind an interface that looks like any other module, is the secret weapon of the C API.
Where the Speed of C Appears
A function written in C is not automatically faster than the expression it replaces, because every call from Python still passes its arguments as Python objects and receives a Python object in return. The following measurement compares an addition written inline, a call to a function implemented in C, operator.add, and a call to a Python function, and then compares a Python loop with the built-in sum, whose loop runs in C.
import operator
import timeit
def py_add(a, b):
return a + b
values = {"a": 50, "b": 25}
inline = timeit.timeit("a + b", globals=values, number=1_000_000)
c_call = timeit.timeit("add(a, b)", globals=dict(values, add=operator.add), number=1_000_000)
py_call = timeit.timeit("add(a, b)", globals=dict(values, add=py_add), number=1_000_000)
print(inline < c_call < py_call) # Output: True
data = {"data": range(100_000)}
loop = timeit.timeit("t = 0\nfor i in data: t += i", globals=data, number=20)
builtin = timeit.timeit("sum(data)", globals=data, number=20)
print(builtin < loop) # Output: True
On the machine used for this article, with CPython 3.12, the inline addition took about 10.5 nanoseconds, the call to the C function about 16.5 and the call to the Python function about 24, while sum processed the hundred thousand integers about 2.7 times faster than the Python loop. A C function that adds two numbers is therefore slower than the operator +, since the cost of the call exceeds the cost of the work; the benefit of C appears when an entire loop, or a call into an existing C library, moves behind a single call from Python. The module built in the following sections adds two integers only because the example isolates the mechanics of the C API.
The C Source of an Extension Module
An extension module consists of C functions with a fixed signature, a table that lists them, a module definition and an initialization function whose name the interpreter derives from the module name. The following file, supermath_module.c, defines a module supermath with a single function add; it requires a C compiler and is built in the next section, not executed directly.
#include <Python.h>
#include <limits.h>
static PyObject *
supermath_add(PyObject *self, PyObject *args)
{
long long a, b;
if (!PyArg_ParseTuple(args, "LL", &a, &b)) {
return NULL; /* TypeError or OverflowError is already set */
}
if ((b > 0 && a > LLONG_MAX - b) || (b < 0 && a < LLONG_MIN - b)) {
PyErr_SetString(PyExc_OverflowError, "result does not fit in a C long long");
return NULL;
}
return PyLong_FromLongLong(a + b);
}
static PyMethodDef supermath_methods[] = {
{"add", supermath_add, METH_VARARGS, "Add two integers in C."},
{NULL, NULL, 0, NULL}
};
static PyModuleDef_Slot supermath_slots[] = {
#if PY_VERSION_HEX >= 0x030D0000
{Py_mod_gil, Py_MOD_GIL_NOT_USED},
#endif
{0, NULL}
};
static struct PyModuleDef supermath_module = {
PyModuleDef_HEAD_INIT,
.m_name = "supermath",
.m_doc = "Arithmetic implemented in C.",
.m_size = 0,
.m_methods = supermath_methods,
.m_slots = supermath_slots,
};
PyMODINIT_FUNC
PyInit_supermath(void)
{
return PyModuleDef_Init(&supermath_module);
}
The function supermath_add receives the arguments as a tuple, and PyArg_ParseTuple converts them into C values according to the format "LL", two long long integers; when the conversion fails, the function has already set a Python exception, and returning NULL makes the interpreter raise it. The explicit check prevents the addition from overflowing in C, where signed overflow is undefined behaviour, and reports the problem as an OverflowError instead. The type long long is deliberate, since long has only 32 bits on Windows, a difference already discussed in the article devoted to ctypes. Older tutorials begin with #define PY_SSIZE_T_CLEAN, which is unnecessary since Python 3.13.
The Module Definition and Its Entry Point
Games that accept modifications load a mod only if it exposes the entry point and the manifest that the game expects, and the game calls that entry point when it loads the mod. An extension module works in the same way: when Python imports supermath, it looks for an exported function named PyInit_supermath, calls it, and reads the returned PyModuleDef, which acts as the manifest of the module. The analogy, however, stops at this point, because a game can usually unload a mod, whereas CPython never unloads the shared library of an extension module once it has been imported.
The definition above uses multi-phase initialization, the form that the tutorial of Python 3.14 presents: the entry point returns the definition through PyModuleDef_Init, and the interpreter creates the module object itself, processing the slots in m_slots. The slot Py_mod_gil with Py_MOD_GIL_NOT_USED declares that the module can run without the global interpreter lock, which matters on the free-threaded build available since Python 3.13; according to the documentation, importing a module that lacks this declaration raises a warning and enables the lock at run time. The function add keeps no state between calls, which is why the declaration is safe here; a module with shared state would first have to protect it.
Building and Importing the Module
Since Python 3.12, the standard library no longer contains distutils, removed by PEP 632, so a build script that imports distutils.core, as many older tutorials do, fails. The documentation now points to third-party tools such as setuptools, with which the build script reads as follows.
# setup.py
from setuptools import Extension, setup
setup(
name="supermath",
version="1.0",
ext_modules=[Extension("supermath", sources=["supermath_module.c"])],
)
The command python -m pip install . compiles and installs the module, and python setup.py build_ext --inplace builds it in the current directory during development. The result is a shared library whose name encodes the interpreter and the platform, such as supermath.cp314-win_amd64.pyd on Windows or supermath.cpython-314-x86_64-linux-gnu.so on Linux. Once built, the module behaves like any other:
import supermath
print(supermath.__doc__) # Arithmetic implemented in C.
print(supermath.add(50, 25)) # 75
try:
supermath.add("hello", "world")
except TypeError as error:
print("TypeError:", error) # raised by PyArg_ParseTuple
try:
supermath.add(2**63 - 1, 1)
except OverflowError as error:
print(error) # result does not fit in a C long long
Both listings of this section require setuptools, a C compiler and the compiled module, so their comments describe the expected behaviour rather than an output verified for this article. Strings are rejected during argument parsing, before any C arithmetic runs, and a sum that exceeds 64 bits produces the OverflowError set by the explicit check.
Pitfalls of Hand-Written Extensions
The C API gives full control over the interaction with the interpreter, and therefore makes every error that Python normally prevents possible again. Six pitfalls are distinguished, which are the following:
- Reference counting. Every Python object created or received in C carries a reference count that the code must increase and decrease correctly; a missing decrement leaks memory, and an extra one crashes the interpreter later, far from the cause.
- The error protocol. A function that fails must set an exception and return
NULL; returningNULLwithout an exception, or a value with an exception set, produces aSystemError. - C integer widths.
longhas 32 bits on Windows and 64 bits on Linux and macOS, and C arithmetic overflows silently unless the code checks it. - One binary per interpreter. A compiled module works only for the version and platform it was built for, unless it is restricted to the limited API and the stable ABI, which the free-threaded build does not yet support.
- Free-threaded builds. A module that does not declare
Py_mod_gilre-enables the global interpreter lock when imported, and a module that declares it must not keep unprotected shared state. - Outdated instructions. Tutorials written before Python 3.12 rely on
distutilsand on single-phase initialization withPyModule_Create, which no longer reflect the recommended practice.
Each of these pitfalls is a reason to prefer a tool that generates the C code, unless the extension needs a degree of control that only the C API provides.
Choosing How to Reach C
Consequently, writing against the C API is the most powerful option and also the most demanding one, and the official documentation itself suggests considering ctypes or cffi before writing custom C code, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Calling a few functions of an existing C library | ctypes or cffi, without compiling anything |
| Speeding up a CPU-bound Python loop | Cython with static types |
| Wrapping a C++ library | pybind11 or a similar binding generator |
| Full control over types, memory and the interpreter | The C API, written by hand |
| A single arithmetic operation | Plain Python, since the call costs more than the work |
The path through Cython, which generates code for this same API, is examined in the article devoted to Cython.
Conclusion
It is concluded that an extension module consists of C functions that convert Python objects into C values and back, a method table, a module definition and an entry point named after the module, and that since Python 3.12 its correct form uses setuptools for the build, multi-phase initialization and an explicit declaration for the free-threaded build. This magic pays off only when a substantial amount of work moves into C behind each call, and it transfers to the author the responsibilities, from reference counts to integer overflow, that the interpreter otherwise assumes. The interpreter itself applies a related economy when it shares a single object for each small integer instead of creating a new one, an instance of the Flyweight pattern, which is developed in a future article of this series.