CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pybind11

Seamless operability between C++11 and Python for creating Python bindings of existing C++ code

Pending
Overview
Eval results
Files

python-package.mddocs/

Python Package API

The pybind11 Python package provides build system integration, path discovery utilities, and helpers for building C++ extensions. This package is typically used during the build process rather than at runtime.

Capabilities

Path Discovery Functions

Functions to locate pybind11 installation paths for build systems and compilers.

def get_include(user: bool = False) -> str:
    """
    Return the path to the pybind11 include directory.
    
    Args:
        user: Unused historical parameter, may be removed
        
    Returns:
        str: Path to pybind11 C++ headers
    """

def get_cmake_dir() -> str:
    """
    Return the path to the pybind11 CMake module directory.
    
    Returns:
        str: Path to CMake modules
        
    Raises:
        ImportError: If pybind11 is not properly installed
    """

def get_pkgconfig_dir() -> str:
    """
    Return the path to the pybind11 pkgconfig directory.
    
    Returns:
        str: Path to pkgconfig files
        
    Raises:
        ImportError: If pybind11 is not properly installed
    """

Version Information

Package version information for compatibility checking.

__version__: str  # Version string (e.g., "3.0.1")
version_info: tuple  # Version tuple (major, minor, patch)

Extension Building Classes

Classes for building C++ extensions with proper pybind11 integration.

class Pybind11Extension:
    """
    Build a C++11+ Extension module with pybind11.
    
    Automatically adds recommended flags and assumes C++ sources.
    Inherits from setuptools.Extension or distutils.Extension.
    """
    
    def __init__(self, *args, cxx_std: int = 0, include_pybind11: bool = True, **kwargs):
        """
        Initialize Pybind11Extension.
        
        Args:
            *args: Arguments passed to Extension
            cxx_std: C++ standard level (11, 14, 17, etc.) - 0 for auto-detection
            include_pybind11: Whether to automatically include pybind11 headers
            **kwargs: Additional keyword arguments passed to Extension
        """
    
    @property
    def cxx_std(self) -> int:
        """The C++ standard level."""
    
    @cxx_std.setter
    def cxx_std(self, level: int) -> None:
        """Set the C++ standard level."""
class build_ext:
    """
    Customized build_ext that allows auto-search for the highest supported
    C++ level for Pybind11Extension.
    
    Inherits from setuptools.command.build_ext.build_ext or
    distutils.command.build_ext.build_ext.
    """
    
    def build_extensions(self) -> None:
        """Build extensions, injecting C++ std for Pybind11Extension if needed."""

Parallel Compilation Utilities

Utilities for accelerating compilation of C++ extensions.

class ParallelCompile:
    """
    Make a parallel compile function for faster builds.
    """
    
    def __init__(
        self,
        envvar: str | None = None,
        default: int = 0,
        max: int = 0,
        needs_recompile: Callable[[str, str], bool] = no_recompile
    ):
        """
        Initialize parallel compilation.
        
        Args:
            envvar: Environment variable to control compilation threads
            default: Default number of threads (0 for auto)
            max: Maximum number of threads (0 for no limit)
            needs_recompile: Function to determine if recompilation is needed
        """
    
    def function(self) -> CCompilerMethod:
        """Build a function object usable as distutils.ccompiler.CCompiler.compile."""
    
    def install(self) -> ParallelCompile:
        """Install the compile function into distutils.ccompiler.CCompiler.compile."""
    
    def __enter__(self) -> ParallelCompile:
        """Context manager entry."""
    
    def __exit__(self, *args) -> None:
        """Context manager exit."""

Helper Functions

Utility functions for extension building and compilation.

def intree_extensions(
    paths: Iterable[str], 
    package_dir: dict[str, str] | None = None
) -> list[Pybind11Extension]:
    """
    Generate Pybind11Extensions from source files in a Python source tree.
    
    Args:
        paths: Source file paths
        package_dir: Package directory mapping (behaves like setuptools.setup)
        
    Returns:
        List of Pybind11Extension objects
    """

def has_flag(compiler, flag: str) -> bool:
    """
    Return True if a flag is supported by the specified compiler.
    
    Args:
        compiler: Compiler instance
        flag: Compiler flag to test
        
    Returns:
        bool: True if flag is supported
    """

def auto_cpp_level(compiler) -> str | int:
    """
    Return the max supported C++ std level (17, 14, or 11).
    
    Args:
        compiler: Compiler instance
        
    Returns:
        str | int: Latest supported C++ standard ("latest" on Windows, int elsewhere)
    """

def naive_recompile(obj: str, src: str) -> bool:
    """
    Simple recompile check based on modification times.
    
    Args:
        obj: Object file path
        src: Source file path
        
    Returns:
        bool: True if recompilation is needed
    """

def no_recompile(obj: str, src: str) -> bool:
    """
    Always recompile strategy (safest but slowest).
    
    Args:
        obj: Object file path (unused)
        src: Source file path (unused)
        
    Returns:
        bool: Always True
    """

Command Line Interface

The package provides a command-line interface for configuration queries.

# Entry point: pybind11-config
# Usage: pybind11-config --includes
#        pybind11-config --cmakedir
#        pybind11-config --pkgconfigdir

Usage Examples

Basic Extension Setup

from pybind11.setup_helpers import Pybind11Extension, build_ext
from setuptools import setup

ext_modules = [
    Pybind11Extension(
        "my_extension",
        ["src/main.cpp", "src/helper.cpp"],
        cxx_std=14,
        include_pybind11=True,
    ),
]

setup(
    name="my_package",
    ext_modules=ext_modules,
    cmdclass={"build_ext": build_ext},
)

Using Parallel Compilation

from pybind11.setup_helpers import ParallelCompile

# Enable parallel compilation
ParallelCompile("NPY_NUM_BUILD_JOBS").install()

# Or use as context manager
with ParallelCompile("NPY_NUM_BUILD_JOBS"):
    setup(...)

Path Discovery in Build Scripts

import pybind11

# Get include path for compiler
include_dirs = [pybind11.get_include()]

# Get CMake directory for CMake-based builds
cmake_dir = pybind11.get_cmake_dir()

# Get pkgconfig directory
pkgconfig_dir = pybind11.get_pkgconfig_dir()

Types

from typing import Callable, Iterable

# Type aliases used in the API
CCompilerMethod = Callable[..., list[str]]
CompilerType = Any  # distutils.ccompiler.CCompiler type

Install with Tessl CLI

npx tessl i tessl/pypi-pybind11

docs

advanced-features.md

core-binding.md

exception-handling.md

index.md

numpy-integration.md

python-package.md

stl-integration.md

type-system.md

tile.json