Packages and rewriting

Why a wheel with an extension is tied to the interpreter version, the platform and the libc — and how that tells you when to move hot code into C or Rust, and when doing so is a pure loss.

L1 · 9 minL2 · 10 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
import sysconfig
print(sysconfig.get_config_var("SOABI"))
print(sysconfig.get_platform())
cpython-311-x86_64-linux-gnu
linux-x86_64
Three coordinates in one name. All three have to match.
Snippet B
import importlib.util
spec = importlib.util.find_spec("numpy._core._multiarray_umath")
print(spec.origin.split("/")[-1])
_multiarray_umath.cpython-311-x86_64-linux-gnu.so
The file name contains the Python version. If it does not match, the module is not found.
Snippet C
# pip install on a machine with no ready-made wheel
pip install some-c-package
Building wheel for some-c-package (pyproject.toml) ... error
error: command 'gcc' failed: No such file or directory
The package installed for years. Today it needs a compiler.
Snippet D
import sysconfig
print(sysconfig.get_config_var("Py_GIL_DISABLED"))
False
On a free-threading build it will be 1 — and that is a different ABI, with separate cp313t wheels.

2Mechanism

From lesson 15 we know: an extension sees Python objects directly — their fields, their reference count, their slots. Here: what follows from that for distributing code.

An extension is a compiled library linked against a specific version of CPython's structures.

ABI is the binary contract: the layout of structures, function signatures, field sizes. It changes from version to version.

A wheel is an archive with compiled contents and tags in its name: the Python version, the ABI, the platform. If even one does not match, the wheel does not fit.

Consequence 1 · a wheel is tied to three coordinates at once

Snippets A and B. The name cpython-311-x86_64-linux-gnu contains the interpreter version, the architecture and the libc variant. The extension file carries this tag right in its name, and import looks it up literally by match.

Hence the combinatorics you can see in any large project: a library with C code releases a separate wheel for every “Python version × platform” pair. Five supported versions, four platforms — twenty builds per release. This is not bureaucracy but a direct consequence of the ABI not being stable.

And hence also manylinux: on Linux, distributions differ in their glibc version, so a wheel is built in an old environment so that it works on new ones too. A tag like manylinux_2_17 means “requires glibc 2.17 or later”.

Consequence 2 · no wheel — a compiler is needed

Snippet C. If no wheel was built for your combination of version and platform, pip tries to build from source — and requires a compiler, the Python headers, and sometimes system libraries too.

This is the most common reason for “it will not install for me, but it does for my colleague”: for the colleague a ready wheel fitted, for you none did. The typical triggers: a fresh Python version that came out before the libraries' releases; Alpine with musl instead of glibc; ARM, when wheels are built only for x86.

The diagnosis is direct: look at what pip downloaded — a .whl or a .tar.gz. The second means a build from source.

Consequence 3 · a stable ABI exists, but it is paid for

Since the problem is the tie to a version, a subset of the API with a compatibility guarantee suggests itself. It exists: the Limited API and wheels tagged abi3, which work on every version from the declared one onward.

The price is that some capabilities are unavailable: structure fields cannot be accessed directly, only through functions. For an extension that computes in its own buffer this costs nothing; for one that works closely with Python objects it is noticeable. That is why abi3 is chosen by libraries that wrap C code, and not by numpy and the like.

Consequence 4 · free-threading is a separate ABI

Snippet D. A build without the GIL changes the layout of objects: fields for biased reference counting are added to the header (lesson 09). So extensions have to be rebuilt, and wheels are marked with a separate tag, cp313t.

Hence an honest assessment of the transition: it is not about installing a different interpreter, but about the whole binary part of the dependencies needing a build for it. The first step of any migration assessment is an inventory of extensions and a check of whether they have such wheels.

And the conclusion about rewriting

Everything listed is the price paid for an extension. So the decision “move hot code into C or Rust” costs not only the writing of the code: a build matrix appears, a compiler in CI, separate wheels per platform, the risk of a segfault instead of a traceback, and the impossibility of debugging with an ordinary debugger. It has to be assessed as a whole, not only by the gain in speed.

3Limits of the model

Where this stops holding

None of this concerns pure Python packages. A wheel tagged py3-none-any works everywhere. All the complexity here is exclusively about binary extensions.

ABI and API are different things. A source that builds on 3.11 and 3.12 is API compatibility. An already compiled file that works on both is ABI compatibility, and that is much stricter.

Tags are not a guarantee that it works. manylinux promises glibc compatibility, but not the presence of the system libraries the extension is dynamically linked against. Hence ImportError: libXXX.so.1: cannot open shared object file with a wheel that formally fitted.

4Root

Root R6: extensions see the internals directly. Everything in this lesson is the bill for that decision. Direct access gave speed and made it possible to wrap any C library in an evening; it also means that compiled code knows the layout of the structures, and so breaks when it changes.

The wheel format (PEP 427, 2012) appeared late — for twenty years the ecosystem lived on source distributions, where installing every package meant compiling. That is exactly why “pip install of a scientific library” once took half an hour and often failed, and conda arose as a way to ship things already built, together with their system dependencies.

The chronology matters for understanding the current state: first there was direct access to structures, then attempts to limit it for the sake of portability (Limited API, 2010), then a format for distributing what was built (wheels, 2012), then a binary-compatibility standard on Linux (manylinux, 2016). Each layer was added on top of a decision made in 1991.

5Analogy

The exact analogy is dynamic linking in C. An extension file is a .so, the ABI tag is the soname version, and manylinux is the same as symbol versioning in glibc: a way to promise that what was built in an old environment will work in a new one.

The symptoms coincide too. A version mismatch in C gives version GLIBC_2.34 not found; in Python, “no matching wheel” or an ImportError on import. And the cure is essentially the same: either build for the target environment, or restrict yourself to a subset with a compatibility guarantee (in C, versioned symbols; in Python, abi3).

There is one difference, and it is about the audience: in C this is faced by whoever builds the program, while in Python it is faced by whoever types pip install and usually knows nothing about ABI.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why does a package with a C extension not install on a new Python?

Because a wheel is tied to the interpreter version, the platform and the libc — and there simply is no matching one.

The name of a wheel file is precisely its compatibility conditions:

numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.whl
        Python ABI  platform and minimum glibc

requests-2.31.0-py3-none-any.whl
                 pure Python — fits everywhere

3.13 came out — cp311 does not fit, and pip does what it should: it downloads the source and tries to build it. Then either there is no compiler (error: command 'gcc' failed), or no headers (Python.h: No such file or directory), or the code does not build against the new version of the C API.

What to look at first:

python -m pip debug --verbose     # which tags this interpreter accepts at all
pip download package --no-deps -d /tmp/w && ls /tmp/w

The first command prints the list of compatible tags from the most specific to the most general; if the package's tag is not there, there will be no wheel.

The practical conclusion for operations: upgrading the minor version of Python means rebuilding the whole dependency matrix, not changing one line in a Dockerfile. That is exactly why the industry sits on version N−1, and exactly why in 3.13 free-threading was made a separate build: it has its own ABI and its own matrix of wheels.

If abi3 solves the version problem, why does not everyone use it?

Because the stable ABI is a subset of the C API, and it lacks exactly what extensions are written for.

abi3 (PEP 384) promises: a wheel built for 3.7 works on 3.8, 3.9, 3.11 and beyond. One wheel per platform instead of one per version — a huge saving.

cryptography-42.0-cp37-abi3-manylinux_2_28_x86_64.whl
                        ↑ built for 3.7, works on all later versions

What it costs. In the stable ABI structure fields cannot be accessed directly — only through functions, and that is slower. There is no access to the internals of PyTypeObject, because of which for a long time types with slots could not be defined properly. Some fast paths such as vectorcall are missing. For numpy or lxml, where every access to an object's field counts, this is unacceptable.

So abi3 is chosen by libraries where the extension is a thin binding around someone else's code: cryptography (a wrapper over OpenSSL), database drivers, bindings. While numpy, pandas and torch build for each version separately and maintain a matrix of wheels.

Useful to know when choosing a dependency: look at the wheel's name. abi3 in the name means that when you upgrade Python this library will almost certainly not become your problem. Its absence means it will.

venv or a container — which, and when?

They solve different parts of one task, and in production you need both.

venv isolates Python dependencies: its own site-packages, its own pip. It isolates neither system libraries, nor the version of Python itself, nor libc. A container isolates all of that and isolates nothing inside itself.

Hence a classic accident that venv does not catch:

FROM python:3.11-slim
RUN pip install opencv-python-headless
CMD ["python", "-c", "import cv2"]
# → ImportError: libGL.so.1: cannot open shared object file

The wheel installed, the dependencies are pinned, but the extension needs a system library that the slim image does not have. venv knows nothing about this in principle.

# what the extension requires from the system
ldd $(python -c "import cv2, pathlib; print(pathlib.Path(cv2.__file__).parent / 'cv2.abi3.so')")
# lines with "not found" are a future ImportError

The practical split. Development on your machine — venv (or uv, poetry): cheap, fast, switches instantly. Production and CI — a container: it pins Python, libc and system packages. Inside a container venv is useful too, but for another reason — so as not to mix with the distribution's system Python.

And neither replaces a lock file: without pinned versions of transitive dependencies there is no reproducibility in a venv or in a container.

Bottom line. An extension is a compiled library linked against a specific layout of CPython's structures, so a wheel is tied to three coordinates at once: the Python version, the ABI, the platform. The file name contains them literally, and import looks them up by match. Hence a matrix of builds for every release, a separate manylinux standard for Linux, and the most common reason for “it will not install for me”: no wheel was built for your combination, and pip went off to compile from source. A stable ABI exists — the Limited API and abi3 wheels — but it is paid for by giving up direct access to structure fields, and so it is chosen by wrappers, not by libraries that work closely with objects. Free-threading changes the object header, that is, it is a separate ABI with the tag cp313t: a migration assessment begins with an inventory of binary dependencies. And this whole bill is the price of the decision from lesson 15: direct access to the internals gave speed and cost portability.
From here on — optional
counterfactualC, C++ and RustThe ABI problem is not Python's — but in Python it is in every pip install

C lives with this always: the ABI depends on the compiler, the flags, the libc version, and on Linux compatibility rests on convention, not on a guarantee. The difference is that there building is an explicit step, where these questions are settled by the developer; in Python it is hidden inside pip install, and it is the library's user who has to sort it out.

C++ makes it worse with name mangling: the ABI depends on the compiler and the standard library as well, which is why object files from gcc and MSVC cannot be mixed. That is exactly why extensions to Python prefer to export a C interface even when there is C++ inside.

Rust solved the same problem radically: it has no stable ABI of its own at all, everything is compiled from source in full, and compatibility is provided at the level of the package manager. For Python extensions (PyO3) this is convenient — the build produces a statically linked artifact anyway, and only the Python part of the matrix remains.

Hence a practical conclusion when choosing a language for an extension: Rust removes part of the pain by not trying to be binary-compatible with anything.

🐛 bugThe image built, the container does not startThe wheel matched by its tags, but a dynamic dependency is missing from the image

The build is green, the tests passed, the production image fails on import.

FROM python:3.11-slim
RUN pip install opencv-python-headless
CMD ["python", "-c", "import cv2"]
ImportError: libGL.so.1: cannot open shared object file:
No such file or directory

The wheel installed without a single warning: the tags matched, the ABI fitted. But the extension is dynamically linked against system libraries that the slim image does not have. manylinux guarantees glibc compatibility and promises nothing about the rest.

Review lets it through because on the developer's machine these libraries are installed by other packages — everything imports there. It breaks only in a minimal image, that is, in production.

RUN apt-get update && apt-get install -y --no-install-recommends \
        libgl1 libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

How to find this ahead of time, without waiting for production:

# what the extension requires from the system
ldd $(python -c "import cv2, pathlib; print(pathlib.Path(cv2.__file__).parent / 'cv2.abi3.so')")
# lines with "not found" are a future ImportError

The rule: every binary extension is checked with ldd in the image where it will run — not where it was built. And importing all the dependencies is worth making a build step: RUN python -c "import cv2, numpy, lxml" breaks the build rather than production.

⚡ decisionRewrite or not — count the whole costThe profile gives the share of time; add to it the build matrix, CI with a compiler, and the loss of the traceback

The question “move the hot piece into Rust?” is decided not by speed but by the full cost.

What goes on the gain side of the scales. Only a profile under production load: what share of the total time the candidate takes. If it is twenty percent, a perfect speed-up gives twenty percent, and that is the ceiling. Before counting further, it is worth checking two cheaper paths: the algorithm (lesson 03: in on a list versus a set — 154×) and vectorization (lesson 15: the same work in numpy plus threads).

What goes on the cost side — straight from the consequences of this lesson:

itemwhat it means
a build matrixa wheel for every “Python version × platform” pair
CI with a compilercross-building, manylinux images, signing artifacts
debugginga segfault instead of a traceback; an ordinary debugger does not help
who fixes ityou need someone who reads that language — usually one person on the team
free-threadingone more branch of the matrix, once you get to it

The order worth going through before rewriting: profile → algorithm → vectorization → threads on whatever releases the GIL → and only then an extension. Each step is an order of magnitude cheaper than the next and often settles the question.

If you do rewrite after all: Rust with PyO3 removes part of the pain — static linking takes away the ldd story, and abi3 cuts the matrix down to one build per platform. A formulation for the team that gets through: “the profile shows N% in this function, the speed-up will give this much, it costs these items, the rollback plan is to keep the Python implementation behind a flag”.

💻 terminalCheck it in the terminalFour snippets plus wheel tags, ldd and building from source

Run the snippets and check them against your prediction. Then, in a terminal:

python -c "import sysconfig; print(sysconfig.get_config_var('EXT_SUFFIX'))"
# What file-name suffix will the compiled module get?

pip download numpy --no-deps -d /tmp/w && ls /tmp/w
# What was downloaded: a .whl or a .tar.gz? What tags are in the name?

python -c "import numpy, pathlib; print(list(pathlib.Path(numpy.__file__).parent.rglob('*.so'))[:3])"
# How many binary modules are inside one package?

pip install --no-binary :all: --dry-run some-package
# What happens if ready-made wheels are forbidden?

The second question is the most practical one: learning to tell “a ready one was downloaded” from “compilation is about to begin” saves hours when taking apart other people's installation problems.

sourcesysconfig and importlib.machineryWhere you can see how the tags get into the file name

Lib/sysconfig.py. This is where all the build variables are collected, including SOABI and EXT_SUFFIX. Read how the extension suffix is formed: the file name by which import finds the module is glued together from the version, the ABI and the platform — consequence 1 as a string.

Lib/importlib/machinery.py. Find EXTENSION_SUFFIXES: the list of suffixes by which binary modules are searched for. It also shows that .abi3.so is on the list — the mechanism of consequence 3 is supported right in import.

PEP 513 and its successors. Not code, but worth reading once for the list of libraries that manylinux allows to be assumed present on the system. Everything not on that list the extension must carry with it or demand from the image — exactly what the bug from the “In practice” section trips over.

L2What a wheel is made of, and how pip choosesCompatibility tags, the order of priority, what is inside the archive

From L1 you know about the three coordinates. Here: how they are written down and compared.

The name of a wheel is built like this: name-version-python-abi-platform.whl. Examples:

requests-2.31.0-py3-none-any.whl
numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.whl
cryptography-42.0-cp37-abi3-manylinux_2_28_x86_64.whl

The first is pure Python and fits everywhere. The second is an extension for a specific CPython 3.11. The third is abi3: built against the Limited API, from 3.7 on, so one wheel for the whole line of versions.

pip builds the list of tags supported by the current environment in order of preference and takes the first matching wheel. You can see the list like this:

python -m pip debug --verbose
# Compatible tags: several hundred lines, from the most specific to the most general

Inside the archive is an ordinary zip: the package as is, plus a *.dist-info directory with metadata, the list of files and checksums. Installation comes down to unpacking; no code is executed when a wheel is installed — unlike a source distribution with setup.py, where everything is executed.

This, incidentally, is a separate argument for wheels besides speed: installing a wheel does not run arbitrary code; installing from source does.

L3Where this is in the sources and standardssysconfig, machinery, PEP 427 and 513

Tag v3.11.15.

  • Lib/sysconfig.py — how SOABI and EXT_SUFFIX are formed.
  • Lib/importlib/_bootstrap_external.py — ExtensionFileLoader and the list of suffixes by which .so files are searched for.
  • PEP 427 — the wheel format; short and entirely readable.
  • PEP 384 — the Limited API and abi3; the motivation lists exactly what has to be given up.
connectionsWhere this leadsL15, L17, L19 · the contrast with dynamic linking in C and the Rust model
root R6 · The C API as the way to extend
← foundation L15 · The boundary with C and zero-copy — the direct access to structures that is paid for here
← foundation L17 · Import, end to end — how import finds a binary module by its file name
↔ contrast Dynamic linking in C: soname and symbol versioning instead of wheel tags
↔ contrast Rust: no stable ABI of its own at all, and that makes life simpler
→ next L19 · The GIL — why free-threading turned out to be a separate ABI
not covered here Environment tools and lock files — that is about reproducibility, not about the language's mechanism
readingFurther readingPEP 427 🟧 · PEP 384 🟦 · packaging.python.org 🟥

Written by · The Python Canon