Skip to content
Latchkey

pip "ModuleNotFoundError: No module named '_ctypes'" (libffi) in CI

The _ctypes extension is compiled into Python only if libffi was present when the interpreter was built. A Python compiled from source on a runner without libffi-dev silently omits it, and any import of ctypes fails.

What this error means

Tools that use ctypes (or anything importing it transitively) fail with "ModuleNotFoundError: No module named '_ctypes'", typically after building Python from source via pyenv on a slim image.

python
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File ".../ctypes/__init__.py", line 8, in <module>
    from _ctypes import Union, Structure, Array
ModuleNotFoundError: No module named '_ctypes'

Common causes

Interpreter built without libffi-dev

When pyenv compiles Python and libffi-dev is absent, the _ctypes module is skipped without erroring the build.

A slim image used to compile Python

Minimal base images lack the system libraries CPython optionally links against, so several stdlib extensions go missing.

How to fix it

Install libffi-dev and rebuild the interpreter

  1. Install libffi-dev (and the standard CPython build deps).
  2. Reinstall the Python version so _ctypes is compiled in.
Terminal
sudo apt-get install -y libffi-dev libssl-dev zlib1g-dev
pyenv install --force 3.12.4

Use a prebuilt interpreter

Prefer actions/setup-python, which provides a complete CPython build with all stdlib extensions present.

.github/workflows/ci.yml
- uses: actions/setup-python@v5
  with:
    python-version: '3.12'

How to prevent it

  • Install the full CPython build dependency set before compiling Python.
  • Prefer prebuilt interpreters over source builds in CI.
  • Validate python -c "import ctypes" right after provisioning the interpreter.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →