When a hot loop must run faster than pure Python, the standard escape hatch is to drop into compiled C code. Python offers several bridges — ctypes is the no-compiler-toolchain one: it talks to any existing shared library (.so / .dll / .dylib) straight from the interpreter.
util.find_library resolves the platform-specific name (libc.so.6 on Linux, libc.dylib on macOS) — prefer it in portable code.
from ctypes import utilfrom ctypes import cdlllibc = cdll.LoadLibrary(util.find_library('libc'))
Shared libraries vs Python modules
ctypes.cdll does not import a Python module — it loads a binary library into the process and exposes its exported functions. There is no type information: you must declare argument and return types.
.raw returns the whole allocated buffer including the NUL terminator (5 bytes); .value returns the C string up to the first NUL (4 bytes). Sizeof is the allocation — that is what C functions will see.
Calling libc functions
libc.printf(spam)
Output:
spam
4
print(libc.rand())
Output:
1025202362
printf returns the character count
The 4 is printf’s return value — the number of characters written, not spam (which is printed as a side effect on the Cstdout). Two gotchas in one example:
C-side output bypasses Python’s sys.stdout buffering — output can appear interleaved or out of order.
By default ctypes assumes the return type is int. If the C function actually returns a pointer or a long, use libc.func.restype = ... — see the exercise below.
Exercise — your own C library
1. Write the C source
// mathlib.clong long factorial(int n) { long long r = 1; for (int i = 2; i <= n; i++) r *= i; return r; // careful: overflows past n = 20}double mean(int *values, int count) { double total = 0.0; for (int i = 0; i < count; i++) total += values[i]; return total / count;}
2. Compile to a shared library
gcc -shared -fPIC -O2 mathlib.c -o libmathlib.so
3. Call it from Python
import ctypeslib = ctypes.CDLL('./libmathlib.so')# Declare the real signatures — the single most important ctypes steplib.factorial.argtypes = [ctypes.c_int]lib.factorial.restype = ctypes.c_longlonglib.factorial(20)
lib2 = ctypes.CDLL('./libmathlib.so')# without restype, ctypes assumes c_int:lib2.factorial(20)
Output:
-2102132736
A silent truncation, not an error
factorial(20) = 2432902008176640000 fits in 8 bytes, but without restype ctypes reads only the low 4 bytes (c_int) — the x86-64 EAX register, so -2102132736. Always declare argtypes and restype. A missing declaration fails silently — the worst kind of bug.
Benchmark: ctypes vs pure Python
import ctypesimport timeitdef py_factorial(n): r = 1 for i in range(2, n + 1): r *= i return rfor fn, label in [(py_factorial, 'python'), (lib.factorial, 'ctypes ')]: t = timeit.timeit(lambda: fn(1_000), number=1_000) print(f'{label}: {t:.4f}s / 1000 calls')
The speed-up here is not because C is faster per se — it is because the entire loop runs in C without touching the interpreter. But ctypes calls carry a fixed per-call overhead (~µs) for argument conversion: calling a trivial C function millions of times can be slower than Python. Move whole computations across the border, not single calls.
Beyond ctypes
Tool
Contract
Best for
ctypes
none — works with any prebuilt .so
gluing existing C libraries, no toolchain
CFFI
C declarations written in Python
cleaner API, better for new C code
Cython
annotate Python code with C types
numerically heavy code, libraries like pandas
pybind11
C++ headers, RAII bindings
exposing C++ classes to Python
maturin/PyO3
Rust + Cargo
safe, high-performance extensions
Same result, different ergonomics
All five produce a native extension importable from Python. ctypes stays the right first tool for this course: it teaches the Python↔C boundary (types, buffers, calling conventions) with zero build infrastructure — everything above it automates those same steps.
Bytecode disassembly with dis
Every function you define in Python is first compiled to bytecode — a list of simple instructions executed by the CPython virtual machine. The dis module (the “disassembler”) shows you exactly what the interpreter will run.
import disdef py_factorial(n): r = 1 for i in range(2, n + 1): r *= i return rdis.dis(py_factorial)
LOAD_FAST / STORE_FAST — read/write a local variable (r, i, n).
LOAD_GLOBAL / LOAD_CONST — fetch a global name or a constant (range, 2, 1).
BINARY_OP — an arithmetic operation (+, *).
FOR_ITER / JUMP_BACKWARD — the loop machinery; everything between them runs once per iteration.
CALL — call a function; each call re-enters the interpreter dispatch loop.
Bytecode vs machine code
Bytecode is not machine code — it is a portable instruction set for the CPython VM. A ctypes call skips all of these instructions on the Python side (see the benchmark above); that is why the whole loop moved to C is faster than the bytecode version.
Why it matters for C extensions
Disassembly makes the interpreter boundary visible:
dis.dis(lib.factorial) # ctypes function
Output:
TypeError: not a function
A ctypes _FuncPtr holds a raw C function pointer — there is no Python bytecode to disassemble. Comparing dis output for the pure-Python version against “nothing” for the C version is a concrete way to see where the interpreter work disappears.
Useful dis API
dis.bytecode(py_factorial) # a bytecode object you can inspectdis.dis(py_factorial, depth=0) # limit nesting (default depth=1 shows nested comprehensions)dis.get_instructions(py_factorial) # iterate Instruction objects programmatically
for ins in dis.get_instructions(py_factorial): if ins.opname == 'BINARY_OP': print(ins.offset, ins.opname, ins.argrepr)
Output:
10 BINARY_OP +
64 BINARY_OP *
Use dis when profiling is not enough
A profiler tells you which function is slow; dis tells you why — e.g. how many LOAD_GLOBAL lookups or CALLs happen per iteration. It is also invaluable when teaching, debugging odd SyntaxWarnings, or comparing CPython versions (bytecode changes between releases, so never depend on it programmatically).
Debugging with pdb
pdb is Python’s built-in interactive debugger — the standard library’s answer to gdb for C. It lets you pause execution, inspect variables, and step through code line by line.
Starting the debugger
Three common entry points:
# 1. From the interpreter or a script — the modern waybreakpoint() # Python 3.7+: drops into pdb at this line
# 2. Explicit import — equivalent, more controlimport pdbpdb.set_trace() # hard-coded trace point
# 3. Run the whole script under the debuggerpython -m pdb myscript.py
breakpoint() is not tied to pdb
breakpoint() honours the PYTHONBREAKPOINT environment variable: PYTHONBREAKPOINT=0 disables all breakpoints, and PYTHONBREAKPOINT=ipdb.set_trace swaps in a third-party debugger. Prefer it over pdb.set_trace() in course code.
Essential commands
Command
Shortcut
Effect
help
h
list commands
next
n
step over the current line
step
s
step into a function call
return
r
run until the current function returns
continue
c
run until the next breakpoint
list
l
show the source around the current line
print expr / pp expr
p / pp
evaluate an expression / pretty-print it
where
w
print the call stack (bottom-up)
up / down
u / d
move up/down the call stack
break lineno
b
set a breakpoint (at a line or function)
quit
q
abort the program
Any other input is evaluated as Python in the current frame — r, lib, data all work as variable names directly at the (Pdb) prompt.
Worked example — debugging the ctypes call
Recall the silent truncation from the exercise above. Here is how you would catch it live:
(Pdb) p result
-2102132736
(Pdb) p lib2.factorial.restype
<class 'ctypes.c_int'>
(Pdb) q
Inspecting restype in the debugger shows it defaulted to c_int — the missing restype declaration is exposed in seconds, instead of after an hour of guessing.
breakpoint() in production code
A forgotten breakpoint() freezes a running program waiting for terminal input. Remove tracepoints before committing, or guard them:
if os.getenv('DEBUG'): breakpoint()
Post-mortem debugging
Run a crashing script with python -m pdb -c continue myscript.py: when the exception is raised, pdb stops in the frame where it happened, with all locals available — the fastest way to debug a traceback you cannot reproduce interactively.