Writing a Python C Extension Module
Build a simple .so extension using the Python/C API.
Writing a Python C Extension Module is a free Python Academy lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.
C Extension Anatomy
A minimal C extension has: method functions, a method table, a module definition struct, and a PyInit_ entry point.
// myext.c skeleton
#include <Python.h>
static PyObject* say_hello(PyObject* self, PyObject* args) {
Py_RETURN_NONE;
}
static PyMethodDef methods[] = {
{"say_hello", say_hello, METH_NOARGS, "Print hello"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT, "myext", NULL, -1, methods
};
PyMODINIT_FUNC PyInit_myext(void) {
return PyModule_Create(&module);
}Parsing Arguments
PyArg_ParseTuple(args, "ii", &a, &b) parses Python arguments into C variables. Format codes: i=int, d=double, s=char*, O=PyObject*.
static PyObject* add(PyObject* self, PyObject* args) {
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b))
return NULL;
return PyLong_FromLong(a + b);
}Returning Values
Build Python return values with: PyLong_FromLong, PyFloat_FromDouble, PyUnicode_FromString, Py_BuildValue.
// Return a Python tuple (int, float)
static PyObject* stats(PyObject* self, PyObject* args) {
int n = 10;
double avg = 5.0;
return Py_BuildValue("(id)", n, avg);
// Py_BuildValue format: i=int d=double s=str
}Reference Counting
Every PyObject* has a reference count. Use Py_INCREF/Py_DECREF carefully. Return values from C functions give the caller ownership (stolen references).
static PyObject* make_list(PyObject* self, PyObject* args) {
PyObject* lst = PyList_New(3);
for (int i = 0; i < 3; i++) {
// PyList_SET_ITEM steals the reference:
PyList_SET_ITEM(lst, i, PyLong_FromLong(i));
}
return lst; // caller owns the list
}Raising Exceptions
Use PyErr_SetString(PyExc_ValueError, "msg") to raise a Python exception from C, then return NULL.
static PyObject* safe_div(PyObject* self, PyObject* args) {
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) return NULL;
if (b == 0) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
return NULL;
}
return PyLong_FromLong(a / b);
}setup.py for C Extensions
Use setuptools.Extension to declare the C source files. Build with python setup.py build_ext --inplace.
# setup.py
from setuptools import setup, Extension
setup(
name="myext",
ext_modules=[
Extension(
"myext",
sources=["myext.c"],
extra_compile_args=["-O2"],
)
]
)
# python setup.py build_ext --inplace
# import myext; myext.add(3, 4)Using the Built Extension
Once built, import the extension like any Python module. Python finds it by looking for myext.so (or .pyd on Windows).
# After: python setup.py build_ext --inplace
import myext
print(myext.add(3, 4)) # 7
print(myext.safe_div(10, 2)) # 5
# myext.safe_div(1, 0) # ZeroDivisionErrorKeyword Arguments
Use PyArg_ParseTupleAndKeywords with a keyword list to support keyword arguments in C functions.
static char* kwargs[] = {"x", "y", NULL};
static PyObject* hypot_c(PyObject* self,
PyObject* args,
PyObject* kw) {
double x, y;
if (!PyArg_ParseTupleAndKeywords(args, kw, "dd",
kwargs, &x, &y))
return NULL;
return PyFloat_FromDouble(sqrt(x*x + y*y));
}Module-Level Constants
Add integer or string constants to the module in PyInit_ using PyModule_AddIntConstant.
PyMODINIT_FUNC PyInit_myext(void) {
PyObject* m = PyModule_Create(&module);
if (!m) return NULL;
PyModule_AddIntConstant(m, "VERSION", 1);
PyModule_AddStringConstant(m, "AUTHOR", "Alice");
return m;
}Releasing the GIL
Wrap pure C work with Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS to let other Python threads run while C code executes.
static PyObject* heavy(PyObject* self, PyObject* args) {
long n;
if (!PyArg_ParseTuple(args, "l", &n)) return NULL;
long result;
Py_BEGIN_ALLOW_THREADS
result = slow_c_computation(n); // GIL released
Py_END_ALLOW_THREADS
return PyLong_FromLong(result);
}Testing the Extension
Test C extensions through their Python interface using pytest. No special C test tools required.
# test_myext.py
import pytest
import myext
def test_add(): assert myext.add(3, 4) == 7
def test_zero_div():
with pytest.raises(ZeroDivisionError):
myext.safe_div(1, 0)Quick Check
What must a C extension function return to signal that a Python exception has been set?
Recap
A C extension needs: method functions (parse args, return PyObject*), a method table, a module def struct, and PyInit_name(). Raise exceptions by setting them with PyErr_SetString and returning NULL. Release the GIL for pure C work.
Learn Python with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 76
- Lessons
- 320
Frequently Asked Questions
Is the “Writing a Python C Extension Module” lesson free?
Yes — the full text of “Writing a Python C Extension Module” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.
What will I learn in “Writing a Python C Extension Module”?
Build a simple .so extension using the Python/C API. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “Writing a Python C Extension Module” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why C Extensions? Use Cases and Trade-offs
- ctypes: Calling C Libraries from Python
- cffi: C Foreign Function Interface
- Writing a Python C Extension Module