polybind
Ayudante para proyectos híbridos de C++/Python: una versión del proyecto, dependencias nativas y clases de Python con distribución de tipos desde códigos auxiliares .pyi
Descargas y Adopción en la Comunidad
Análisis de Salud e Ingeniería (5 Pilares)
1. Gobernanza y Comunidad50 / 200 ▾
2. Metadatos y Empaquetado PEP200 / 200 ▾
3. Seguridad y Cadena de Suministro150 / 200 ▾
4. Documentación, SEO y Ecosistema105 / 200 ▾
5. Ingeniería, CI y Calidad165 / 200 ▾
Documentación Oficial y Guía de Uso — polybind
Mostrar documentación original completa (README en inglés) ▾
polybind
Helper for hybrid C++/Python projects: one version for the whole project, native dependencies, and a generator (
polybind wrap) that turns C++ template variants from a.pyistub into one Python class.
What is in the box
| command | what it does |
|---|---|
polybind version |
show, change and tag the project version (header, pyproject.toml, git tags) and keep the files that repeat it in step |
polybind deps |
declare, resolve, lock and install the native dependencies of a project |
polybind config |
print the effective settings and where each one came from |
polybind cmake-dir |
print the directory of PolybindDeps.cmake for include() |
polybind wrap |
one Python class for the C++ template variants in a .pyi stub (the rest of this page) |
polybind vendor |
copy the C++ dispatch helpers (headers and CMake config) into a project that must build without polybind installed |
polybind/dispatch.hpp |
C++ header-only helpers: one Python name for a function that works on several kinds of data (below) |
Settings live in polybind.toml or [tool.polybind]; see spec.md.
polybind wrap: the problem
Every C++ binding tool forces you to expose each template specialisation as a
separate class. For Box<T> you get:
import _mylib
b_int = _mylib.Box__int32(10)
b_float = _mylib.Box__float64(3.14)
isinstance(b_int, _mylib.Box__int32) # True
isinstance(b_int, _mylib.Box__float64) # False — different class!
For multi-parametric templates like Pair<T1, T2> it gets worse:
p = _mylib.Pair__float64__int32(3.14, 5)
# Which class is this? How do I dispatch on both types at once?
Python users expect a single Box or Pair that dispatches on input
types and where isinstance(obj, Box) works for all specialisations.
polybind wrap: the solution
polybind reads the .pyi stub your binding tool already produces and
generates a clean, fully-typed Python wrapper — no C++ changes needed.
from mylib import Box, Pair
# single-type
b = Box(10)
type(b) is Box # True ✅
isinstance(b, Box) # True ✅
b.value() # 10 ✅
# multi-type
p = Pair(3.14, 5)
p.first() # 3.14 ✅
p.second() # 5 ✅
type(p) is Pair # True ✅
# explicit dtype control
Box(1, dtypes=["float64"]) # force float64 variant
Pair(1, 2, dtypes=["int32", "int64"]) # explicit per-type
Pair(1.0, 2, dtypes={"first": "float64"}) # partial — second auto-detected
# subscript access to raw C++ class
Box["int32"] # → _mylib.Box__int32
Pair[("float64", "int32")] # → _mylib.Pair__float64__int32
Because polybind works from the .pyi stub, it is binding-method agnostic:
the same command works for nanobind, pybind11, and Cython.
C++ dispatch helpers
polybind wrap is for classes. For a function that works on several kinds of data (an image class, a uint8 array, a
float32 array), polybind/dispatch.hpp registers one overload per kind from one generic lambda:
#include <polybind/nanobind.hpp> // the nanobind backend; it includes polybind/dispatch.hpp
polybind::def_dispatch(m, image_cls, "equalize_inplace", my_kinds,
[](auto& x, my::tone_mode mode) -> auto& { return my::equalize_inplace(x, mode); },
"img"_a, "mode"_a = "luma", "doc");
lib.equalize_inplace(x) # x: an Image, a uint8 array or a float32 array; the same object comes back
img.equalize_inplace().gamma_inplace(2.2) # and the method of the class chains
lib.equalize_inplace(x, mode="luma") # an enum is given by name (any case) or as itself; a bad name is a ValueError
What it does for every call:
- One overload per kind of the list
my_kinds = polybind::kinds<Image, Array8, Array32>, in that order. The lambda is instantiated once for each. Another type (float64, int32, a list...) matches none: aTypeError. - An array is received without conversion (
polybind::strict<...>): a float64 array does not become a uint8 one, a non-contiguous array is not copied, a read-only one is refused for a function that changes it. - The first parameter is
auto&(the function changes its argument and gives it back). It returnsvoidor a reference to that argument; the Python call then returns the very same object, so calls chain. Returning another object is an error when it runs. - The other parameters have concrete C++ types: they are converted from Python before the lambda runs, and the GIL is
released around it. An enum
Ewith apolybind::enum_names<E>specialisation is given by name or as itself; a secondconst auto¶meter is a second value of the same kind. - At import, the name is checked against the lambda (
POLYBIND_LINT, on by default): a name that ends with_inplacemust belong to a lambda that changes its argument, and the other way round. A mismatch is aRuntimeWarning(an error under-W error, which is how the tests of a project run).
The project says how each kind is seen from Python by specialising polybind::nanobind_backend::kind<K> (a few lines per
kind; see tests/data/dispatch_module.cpp for a complete toy module). Nothing in the headers knows about the project; they
use no binding library but the backend header you include (nanobind today).
CMake. The target polybind::polybind only adds the include path: it finds and links no binding library.
execute_process(COMMAND "${Python_EXECUTABLE}" -m polybind cmake-dir OUTPUT_VARIABLE _d OUTPUT_STRIP_TRAILING_WHITESPACE)
find_package(polybind CONFIG REQUIRED PATHS "${_d}" NO_DEFAULT_PATH) # from the installed package
target_link_libraries(my_module PRIVATE polybind::polybind)
Without polybind at build time: polybind vendor third_party copies dispatch.hpp, nanobind.hpp and
polybind-config.cmake to third_party/polybind/ with a VENDORED stamp (version and sha256 of each file), and the project
uses include(third_party/polybind/polybind-config.cmake), which defines the same target. polybind vendor --check third_party exits 1 when a file is missing, was edited, or is not the installed polybind's. -DPOLYBIND_LINT=OFF turns
the import-time check off for a project (for what links the target; it defines POLYBIND_LINT=0).
Naming convention
polybind recognises class names using double-underscore separators and numpy scalar type suffixes:
[_]BaseName__T1[__T2[__T3...]]
| Class name | Template | Arity |
|---|---|---|
_Box__int32 |
Box<int32> |
1 |
Box__float64 |
Box<float64> |
1 |
_Pair__float64__int32 |
Pair<float64, int32> |
2 |
Transform__int32__bool_ |
Transform<int32,bool> |
2 |
Supported numpy-style suffixes: int8, int16, int32, int64,
uint8–uint64, float32, float64, bool_, str_, bytes_
(and short aliases int, float, bool, str).
Installation
pip install polybind
Quick start
1 — Expose your C++ templates
// nanobind example
nb::class_<Box<int32_t>>(m, "_Box__int32")
.def(nb::init<int32_t>())
.def("value", &Box<int32_t>::value);
nb::class_<Box<double>>(m, "_Box__float64")
.def(nb::init<double>())
.def("value", &Box<double>::value);
2 — Generate the stub
# nanobind
python -m nanobind.stubgen -m _mylib -o _mylib.pyi
# pybind11
pybind11-stubgen _mylib -o .
# Cython
cython --annotate mylib.pyx # then use stubgen on the .so
3 — Run polybind
polybind wrap _mylib.pyi # writes mylib.py next to the stub
polybind wrap _mylib.pyi -o src/mylib.py
4 — Use the wrapper
from mylib import Box
b = Box(42)
b.value() # 42
Box["int32"] # the raw C++ class
dtypes parameter
The dtypes argument controls which C++ variant is selected:
dtypes value |
Behaviour |
|---|---|
None (default) |
Auto-detect from type(arg) for each constructor argument |
["float64", "int32"] |
Explicit list in template-parameter order |
{"first": "float64"} |
Partial dict — unlisted args auto-detected |
When the number of template parameters exceeds the number of constructor
arguments (e.g. a tag-dispatch pattern), dtypes as a list is required.
The generated wrapper will raise a descriptive TypeError at runtime if
dtypes=None is used in that case.
numpy np.dtype objects are also accepted in any position:
import numpy as np
Box(1, dtypes=[np.dtype("float64")])
What gets generated
For a stub containing _Box__int32, _Box__float64, _Box__str_:
import typing
import _mylib
from abc import ABC as _ABC
_NUMPY_TYPE_MAP: typing.Dict[str, type] = {"int8": int, ..., "float64": float}
class Box(_ABC):
"""Unified wrapper for Box template variants.
Wraps: ``_Box__float64``, ``_Box__int32``, ``_Box__str_``
...
"""
__slots__ = ('_impl',)
_type_map_box: typing.ClassVar[typing.Dict[tuple, type]] = {
('float64',): _mylib._Box__float64,
('int32',): _mylib._Box__int32,
('str_',): _mylib._Box__str_,
}
def __new__(cls, val, dtypes=None) -> 'Box': ...
def value(self): ... # all public methods from the stub
def __add__(self, other): ... # all dunders from the stub
@staticmethod
def zero() -> 'Box': ... # @staticmethod reproduced
@classmethod
def from_string(cls, s) -> 'Box': ... # @classmethod reproduced
@classmethod
def __class_getitem__(cls, item) -> type: ...
for _t in Box._type_map_box.values():
Box.register(_t)
Properties of the generated wrapper:
| Check | Result |
|---|---|
type(obj) is Box |
✅ True |
isinstance(obj, Box) |
✅ True (also for raw C++ objects) |
obj.any_cpp_method() |
✅ delegated directly |
Box(val, dtypes=["float64"]) |
✅ explicit dtype override |
Box["int32"] |
✅ returns the underlying C++ class |
@staticmethod, @classmethod, @property |
✅ reproduced |
| Docstrings from stub | ✅ included and rewritten |
np.dtype for dtypes arg |
✅ if numpy installed |
Multi-type template Pair(1.0, 2) |
✅ auto-detected |
CLI reference
usage: polybind wrap [-h] [-o OUTPUT.py] [-m NAME] [--dry-run] [-v] INPUT.pyi
positional arguments:
INPUT.pyi the .pyi stub file to process
options:
-o, --output OUTPUT.py output .py file (default: INPUT.py next to the stub, leading _ stripped)
-m, --module-name NAME the C-extension module name used in the import statements
--dry-run print the generated code; write no file
-v, --verbose print the groups and variants that were found
Python API
from polybind.core import PolybindGenerator
from pathlib import Path
gen = PolybindGenerator(Path("_mylib.pyi"))
gen.run(output_path=Path("mylib.py"))
# or inspect without writing
source = gen.generate_source()
groups = gen._parser.parse()
for g in groups:
print(g.base_name, g.arity, [v.suffix_key for v in g.variants])
Project layout
polybind/
__init__.py
__main__.py ← CLI
core.py ← StubParser + CodeGenerator + PolybindGenerator
tests/
test_core.py
test_cli.py
data/
_my_module.pyi ← fixture: single and multi-type templates
_my_module.py ← pure-Python stand-in for the C extension
pyproject.toml
README.md
Running tests
pip install -e ".[dev]"
pytest
pytest --cov=polybind --cov-report=term-missing
Author
Mohammad Raziei — MIT License
Project version, settings and dependencies
The design is in spec.md.
Every command has its own help: polybind -h lists them, polybind deps install -h shows one.
Exit codes: 0 success, 1 a check did not pass (version check), 2 a problem you can fix (printed as
polybind: error: ...), 3 a bug in the generator.
polybind version # show X.Y.Z
polybind version minor + # minor += 1 (also: -, +N, -N, N)
polybind version set 1.2.3 # the whole version
polybind version tag create minor # bump, commit the version file, tag vX.Y.Z
polybind version sync # write the version into the [[version.sync]] files
polybind version check # exit 1 if a [[version.sync]] file or the latest git tag differs
polybind config # show the effective settings
polybind deps validate # check settings, dependencies and polybind.lock
polybind deps list [--json] # the dependencies with every default filled in
polybind deps requirements --kind build|runtime|extra:<group> [--with-pyproject]
polybind deps install [--all] # build + runtime requirements of pyproject.toml and [deps] into the environment
The version lives in a header with #define <PREFIX>VERSION_MAJOR|MINOR|PATCH <N> or in the
static version of pyproject.toml; it is detected, or set explicitly.
Files that cannot read it (Cargo.toml, build.zig.zon, a README snippet) are listed as [[version.sync]]: a file
and a regex with the named group (?P<version>...), nothing else. Every command that writes the version writes
them too, tag create commits them, check compares them. A regex that stops matching is an error, and then no file
changes (details: spec.md, 4.2):
[[tool.polybind.version.sync]]
file = "Cargo.toml"
regex = '(?m)^version = "(?P<version>[^"]*)"'
Settings go in polybind.toml or in [tool.polybind] of pyproject.toml (same keys); the command
line wins over polybind.toml, which wins over pyproject:
schema = 1
[version]
file = "include/httpp/version.h"
prefix = "HTTPP_"
tag-format = "v%s"
[deps.liburlparser] # a native library with a CMake package; every key is optional
version-spec = ">=2.2.0,<3"
targets = ["liburlparser::urlparser"]
python.commands.cmake-dir = "<PYTHON> -m <MODULE> --cmake-dir" # a python.* table turns the pip/uv provider on; this is the default
# python.commands.version = "<PYTHON> -m <MODULE> --version" # the default; "" reads the package metadata; a console script works too, e.g. "tool --version"
fetch.url = "https://github.com/mohammadraziei/liburlparser.git" # fetch.url turns the git provider on
Dynamic version. With dynamic = ["version"] in [project], the version is read from the header (the [version] settings are the same as for polybind version): scikit-build-core through the provider below, hatch with
[tool.hatch.version]
source = "polybind"
Letting pip install . (and python -m build) take the requirements from these settings (scikit-build-core): put polybind in [build-system].requires and add the provider; the build requirements go into the isolated build environment and the runtime ones into the wheel metadata (details: spec.md 7.2).
[build-system]
requires = ["scikit-build-core", "polybind"]
build-backend = "scikit_build_core.build"
[project]
dynamic = ["dependencies"]
[[tool.dynamic-metadata]]
provider = "polybind.metadata"
[tool.scikit-build]
sdist.include = ["polybind.toml"]
polybind.lock is a separate file, written only by polybind deps record (the polybind_deps_record target).
Resolving the dependencies in a CMake project (Python is needed at configure time; the settings are TOML and are read by python -m polybind):
execute_process(COMMAND python -m polybind cmake-dir OUTPUT_VARIABLE _d OUTPUT_STRIP_TRAILING_WHITESPACE)
include("${_d}/PolybindDeps.cmake")
polybind_deps_load()
polybind_resolve_dep(liburlparser) # afterwards the targets of [deps.liburlparser] exist
polybind_deps_record_target() # after the tests: cmake --build . --target polybind_deps_record
Reading TOML uses tomllib (Python 3.11+) or tomli, which is installed automatically on
older Pythons.