Ship Compiled Python Wheels Automatically on Every Release
The tag is pushed, the changelog is written, the release notes are published — and the wheel attached to that release was built by hand, on someone’s laptop, three weeks ago. Nobody noticed because nothing broke yet.
That’s the failure mode of manual code protection: not a dramatic crash, just a slow drift where the artifact users download stops matching the code you wrote. This article is about eliminating that drift — a pipeline that produces a freshly compiled Python wheel every single time you cut a release, on every platform, with no Cython knowledge required.
The Manual Release Grind: Why Compiled Wheels Get Skipped
Compiling your own Python is not hard once; it’s hard repeatedly. A manual release looks like this:
- Remember that this release needs a compiled wheel (and not just an sdist).
- Open the Windows machine, run the build, copy the
.whloff it. - Repeat on Linux — and remember
auditwheelfor manylinux compatibility. - Repeat on macOS for ARM64.
- Upload three files by hand, hoping nobody renamed
dist/in between. - Realize two days later that the wheel on the release page was built from
mainbefore the last hotfix merged.
The real risk isn’t the tedium. It’s that the step is optional in practice. When the release is already late, the compiled wheel is the first thing that gets deferred — so you ship readable .py files, or a stale binary that no longer matches the version string. Either way, your protection silently degrades and nothing in your CI fails.
The fix is to make compilation a consequence of tagging, not a task someone remembers. Py2Native is a Python-to-native compiler that turns your plain Python into native machine code — no Cython syntax, no .pyx/.pxd hand-writing, no manual cythonize step — which means the whole thing fits into one CI command. (If you want the background on why the underlying transpiler exists at all, see What Is Cython, and Do You Need It to Compile Python?; here we only care about automating it.)
One-Time Setup: Prepare Your Project for Automated Compilation
Install Py2Native with uv
Add the open-source compiler (MIT licensed) to your project:
uv add py2native
uv add cython setuptools
uv is not optional here — Py2Native uses it to manage the pristine build environment and, in embed mode, the deployment directory. Proceeded by --embed or --wheel, Py2Native calls uv itself, so the same package manager needs to be present on the runner. GitHub runners: astral-sh/setup-uv.
You also need a platform C toolchain on the build machine: MSVC on Windows, GCC on Linux, Clang on macOS. That’s the only native dependency. Supported targets are x86-64 or ARM64, on Windows 8+, manylinux2014/musl Linux, or macOS, with CPython 3.11–3.15 (free-threaded 3.14t and 3.15t included).
Shape the project so the build can glob it
Py2Native compiles what you point it at. Two constraints from the compiler:
- No duplicate module names across source files — the flat compile step can’t disambiguate two
utils.py. __init__.pyis skipped during compilation; it’s a namespace marker, not compilable code.- In library mode,
__main__.pyis excluded from sources — the wheel builder generates it.
A layout that works well:
mypkg/
├── __init__.py # namespace marker, not compiled
├── __main__.py # entry point for `python -m mypkg`
├── startup.py # license check (Pro, optional)
└── core.py
main.py # main module
Add one build command
The whole build is a single invocation. Put it in a script or a Makefile target so CI and humans run the same thing:
# build-wheel.sh
uv run py2native build main.py "*.py" --library --wheel dist
Quoting "*.py" matters: Py2Native expands glob patterns itself under --base, so the shell shouldn’t pre-expand them differently per platform. --library produces a shared library (.pyd/.so/.dylib) instead of an executable; --wheel dist wraps it in a PEP 427 wheel.
Pro only: bake in license verification
If you sell licensed software, the Pro package (py2nativepro, proprietary) adds signed JWT license checks. Install it, then declare the verifier interface in a .pxd file next to your sources:
# p2n_license.pxd
from _p2n_bootstrap cimport _runtime_verify_es256_jwt
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)
At runtime the call is plain Python:
# mypkg/startup.py
def check_license(licenseString: str) -> None:
license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
if not license:
raise SystemExit("Invalid or expired license")
The Pro plugin bakes the ES256 signature verification code and the public key into the executable at build time — only the public key ships, and verification runs in compiled code with no third-party crypto library. That’s the maximum-security, minimum-configuration path. Doing the equivalent by hand means writing a C extension plus your own ECDSA math; Py2Native’s way is a .pxd and one call.
Generate the keypair and a license once:
uv run py2native keygen private.pem public.pem
uv run py2native sign --private private.pem payload.json license.dat
uv run py2native show --public public.pem license.dat
Keep private.pem offline. Only public.pem and the resulting license.dat belong in CI.
The Automated Pipeline: Trigger, Build, and Publish on Every Release
Here’s a GitHub Actions workflow that does the whole job on a tag push. Three runners, two Python versions, artifacts always attached.
name: release-wheels
on:
push:
tags: ["v*"]
release:
types: [published]
permissions:
contents: write
jobs:
build:
name: ${{ matrix.os }} / py${{ matrix.python }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python: ["3.11", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
with:
enable-cache: true
- name: Install interpreter
run: uv python install ${{ matrix.python }}
- name: Materialize license files
if: ${{ vars.PRO_BUILD == 'true' }}
shell: bash
env:
P2N_LICENSE: ${{ secrets.P2N_LICENSE }}
P2N_PUBLIC_KEY: ${{ secrets.P2N_PUBLIC_KEY }}
run: |
printf '%s' "$P2N_LICENSE" > license.dat
printf '%s' "$P2N_PUBLIC_KEY" > public.pem
- name: Build compiled wheel
shell: bash
run: |
uv run --python ${{ matrix.python }} py2native build main.py "*.py" \
--library --wheel dist \
${{ vars.PRO_BUILD == 'true' && '--license license.dat --public public.pem' || '' }}
- name: Smoke test the wheel
shell: bash
run: |
WHL=$(ls dist/*.whl | head -n 1)
echo "testing $WHL"
uv run --isolated --with "$WHL" python -c "import mypkg; print(mypkg.__file__)"
uv run --isolated --with "$WHL" python -m mypkg --version
- uses: actions/upload-artifact@v4
with:
name: wheel-${{ matrix.os }}-py${{ matrix.python }}
path: dist/*.whl
if-no-files-found: error
publish:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Attach wheels to the release
env:
GH_TOKEN: ${{ github.token }}
run: gh release upload "${GITHUB_REF_NAME}" dist/*.whl --clobber
A few things worth calling out:
--licenseand--publicare build-time flags. The Pro plugin validates the JWT during the build; the resulting binary verifies user licenses at runtime with the baked-in public key. There is no runtime configuration to forget.- The wheel is self-contained. In library mode it ships the compiled shared library plus
__init__.py(the meta-path finder that redirectsimport mypkg.submoduleinto the native library) and__main__.py(sopython -m mypkgworks). Both are required — don’t strip them from the wheel. - One job per platform is the point. Wheels are platform-tagged, not universal. If you only build on Linux, macOS users get nothing.
For environments outside GitHub, the same three steps apply in any CI: install uv, run uv run py2native build ... --wheel dist, upload dist/*.whl. GitLab, Buildkite, and Azure Pipelines all express that fine. A sibling article covers the GitHub-specific wiring in more depth: Automate Python Code Protection in GitHub Actions with uv.
Monitoring and Failure Handling: Keep Releases Reliable
A pipeline nobody watches is just a manual process with extra steps. Three layers keep it honest.
1. Fail loudly, notify immediately. Add a notifier on failure so a red release is visible within minutes, not at the next customer ticket:
- name: Notify on failure
if: failure()
uses: slackapi/slack-github-action@v2
with:
webhook: ${{ secrets.SLACK_WEBHOOK }}
webhook-type: incoming-webhook
payload: |
{"text": "Compiled wheel build failed: ${{ matrix.os }} / py${{ matrix.python }} — ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"}
2. Smoke test inside the build job. The step above installs the freshly built wheel into an isolated environment and imports it. The repository ships a smoketest.py you can adapt — it builds with a smoke test rather than only checking exit codes. Failure here means the wheel is broken, not that the compiler errored.
3. Treat platform failures as their own class. The usual suspects are environmental, not code:
- Missing or wrong toolchain — MSVC not on
PATHon Windows runners, nogccin a slim container image. auditwheelon Linux — the Pro/core Linux plugin runs auditwheel repair to make the wheel manylinux-compliant; if it fails, the wheel is technically built but won’t install broadly.- Network access — Py2Native downloads the CPython distribution and the runtime library it links against. Air-gapped runners need a mirror; otherwise you get a compile error that is really a download error.
Log everything, keep artifacts for at least a release cycle (retention-days on the upload step), and let fail-fast: false finish the matrix so one bad runner doesn’t hide a second failure. For transient download or registry hiccups, a single retry loop around the build command is usually enough — just make sure the retry doesn’t mask a deterministic compiler error.
Best Practices for Automated Compiled Wheel Releases
- Pin everything, commit the lockfile.
uv.lockpinspy2native,cython >= 3.2.4,setuptools >= 82.0.1, andauditwheel >= 6.6.0. Commit it and let CI use it — a silently upgraded transpiler is a silently different binary. - Cache the slow parts.
enable-cache: trueon theuvsetup step handles package and interpreter downloads; the rest is your platform toolchain, which runners already have warm. - Tag consistently. The pipeline triggers on
v*. If a release is ever cut without a matching tag, no wheel gets built — make the tag the single source of truth for “this is shippable”, and use semantic versioning sov2.1.0is unambiguous. - Compile only your code. Third-party libraries stay as Python source, unmodified — Py2Native doesn’t rewrite them, and that’s deliberate: it keeps builds simple and keeps LGPL dependencies replaceable by the end user for compliance. Your proprietary modules are what go native. Monkey-patching is still possible against those unmodified libraries, so don’t confuse “my code is compiled” with “nothing can be intercepted”.
- Test installation in a clean environment, not just import.
uv run --isolated --with ./dist/mypkg-...whlgives you a throwaway venv; do it on each platform at least once per release cycle, before users do it for you. - Keep the wheel contents honest.
__init__.pyand__main__.pymust survive any post-processing step you add. If you repack the wheel, verify both are still there.
If you also ship containers, the wheel is usually the better artifact: build once in CI, install the wheel into a minimal runtime image, and skip compilation inside the Docker build entirely. That pattern is covered in How to Protect Python Code in Docker Container Deployments.
FAQ
Can I build wheels for multiple Python versions in one pipeline? Yes. Py2Native supports CPython 3.11–3.15, including free-threaded builds. Use a CI matrix to run the build for each Python version, producing separate wheels. Just ensure each job uses the correct Python interpreter and compiler.
How do I handle license verification in an automated build?
With the Pro plugin, include a .pxd file and call _runtime_verify_es256_jwt in your code. During the build, pass --license with your JWT license file and --public with your public key. The plugin bakes the verification code and public key into the executable, so no extra steps are needed at runtime.
What if my project has dependencies that need special build steps? Py2Native leaves third-party libraries unmodified, so they work as-is. If a dependency requires compilation, ensure your CI environment has the necessary build tools. For most pure-Python dependencies, no extra configuration is needed.
Is Py2Native suitable for open-source projects? Py2Native is designed for protecting proprietary code. While the core compiler is open source (MIT), using it to compile your own code into native binaries is typically for closed-source distribution. For open-source projects, you generally don’t need compilation for protection.
Ship It Once, Then Stop Thinking About It
The value here isn’t the first automated build — it’s the twentieth. Once the pipeline exists, “did we ship a compiled wheel?” stops being a question anyone has to ask, and stale binaries stop being possible. You write plain Python, tag a release, and get platform wheels with native code inside.
Start with the one-time setup: uv add py2native, add the --wheel dist build command to a script, and copy the workflow above. Then decide whether you need the Pro plugin’s JWT verification — if you sell licenses, you probably do. Full interface details, including the CLI, runtime API, and build artifacts, are in the documentation — and if you’re still weighing approaches, Best Python Code Obfuscation and Protection Tools puts compilation in context against the alternatives.
Related posts
- How to Protect Python Code in Docker Container Deployments
- What Is Cython, and Do You Need It to Compile Python?
- Best Python Code Obfuscation and Protection Tools