Python "ModuleNotFoundError: No module named '_ctypes'" in CI
The interpreter was compiled (often via pyenv) without libffi’s development headers, so CPython silently skipped building the _ctypes extension. Anything importing ctypes then fails at runtime.
What this error means
Importing ctypes (directly or via a dependency) fails with ModuleNotFoundError: No module named '_ctypes'. The interpreter otherwise works - only this C extension is missing because libffi was absent at build time.
ModuleNotFoundError: No module named '_ctypes'
# during a pyenv build you may have seen:
# WARNING: The Python ctypes extension was not compiled. Missing the libffi lib?Common causes
libffi dev headers missing at build time
When Python was compiled from source without libffi-dev/libffi-devel, the _ctypes module is skipped. The resulting interpreter has no ctypes support.
A pyenv/from-source build on a slim image
Building the interpreter on a minimal image without the libffi headers reproduces this every time until the headers are installed and Python is rebuilt.
How to fix it
Install libffi headers, then rebuild the interpreter
Add the dev package and recompile Python so _ctypes is built in.
# Debian/Ubuntu
apt-get update && apt-get install -y libffi-dev
# then rebuild, e.g. with pyenv
pyenv install 3.12.4Or use a prebuilt interpreter
A distro or actions/setup-python interpreter already includes _ctypes, avoiding the from-source build entirely.
- uses: actions/setup-python@v5
with:
python-version: '3.12'How to prevent it
- Install all of CPython’s build dependencies (incl.
libffi-dev) before building from source. - Prefer prebuilt interpreters in CI over compiling per job.
- Watch pyenv build warnings - skipped modules are reported there.