Skip to content

Call native code from Python

Build the extensions once and try two versions of the same function. Follow the binding comparison to see what crosses the Python/native boundary in each version.

Install the toolchain

Use CPython 3.11 through 3.15. The repository selects CPython 3.15 by default, and uv can provision it. Install uv and stable Rust with Cargo. uv installs the Python build backends, binding generators, and development tools. You also need a C and C++17 compiler and zlib development files.

Platform Native prerequisites
macOS Install Xcode Command Line Tools with xcode-select --install. The macOS SDK supplies zlib.
Ubuntu / Debian Install the compiler, Make, and zlib headers with sudo apt-get install build-essential zlib1g-dev.
Windows x64 Install Visual Studio Build Tools with Desktop development with C++, the Windows SDK, and the MSVC Rust toolchain. Install zlib using vcpkg.

On Windows, run the following in a Developer PowerShell with vcpkg on your PATH. Set the root to your vcpkg checkout first. The static zlib build uses the same dynamic C runtime as CPython.

$env:VCPKG_ROOT = 'C:\src\vcpkg'
vcpkg install zlib:x64-windows-static-md --classic
$env:CMAKE_TOOLCHAIN_FILE = "$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
$env:CMAKE_ARGS = "-DVCPKG_TARGET_TRIPLET=x64-windows-static-md"

Build and run

From the repository root, run these commands on any supported platform. The first sync compiles a C/C++ package with scikit-build-core and a Rust package with maturin. Later syncs reuse the builds until their inputs change.

uv sync --locked
uv run --locked python -m pytest
uv run --locked python

At the Python prompt, compare the two C++ bindings and Rust.

>>> from native_examples import pybind_fib, nanobind_fib
>>> import rust_fibonacci
>>> [m.compute_fibonacci(20) for m in (pybind_fib, nanobind_fib, rust_fibonacci)]
[17711, 17711, 17711]

Develop locally

With Make installed, use make hooks once to install prek, make check to run the hooks across the repository, and make test after editing code. The Python and Cargo lockfiles are committed. To test another supported interpreter, set UV_PYTHON to the desired version before running Make, or run uv run --locked --python 3.11 python -m pytest.

The prek hook formats staged Markdown with Prettier. To format all tracked Markdown, including the README and this guide, run uv run --locked prek run prettier --all-files. Review and stage the changes before committing. The GitHub Actions quality job runs the same hook across the repository.

Run make docs for a live preview and make docs-test for a strict build. GitHub Actions builds the documentation on pull requests and uploads the rendered site as an artifact. A merge to main publishes the site through GitHub Pages.

Continue to the worked examples and optional exercises.