API reference

Autogenerated from the source docstrings. This documents cppwg’s internals for contributors; most users only need the Configuration reference.

Generator

The main interface for generating Python wrappers.

class cppwg.generators.CppWrapperGenerator(source_root: str, source_includes: list[str] | None = None, wrapper_root: str | None = None, castxml_binary: str | None = None, package_info_path: str | None = None, castxml_cflags: str | None = None, castxml_compiler: str | None = None, overwrite: bool = False)[source]

Main class for generating C++ wrappers.

source_root

The root directory of the C++ source code

Type:

str

source_includes

The list of source include paths

Type:

list[str]

wrapper_root

The output directory for the wrapper code

Type:

str

castxml_binary

The path to the castxml binary

Type:

str

castxml_cflags

Optional cflags to be passed to castxml e.g. “-std=c++17”

Type:

str

castxml_compiler

Optional compiler path to be passed to CastXML

Type:

str

package_info_path

The path to the package info yaml config file; defaults to “package_info.yaml”

Type:

str

source_ns

The namespace containing C++ declarations parsed from the source tree

Type:

pygccxml.declarations.namespace_t

package_info

A data structure containing the information parsed from package_info_path

Type:

PackageInfo

overwrite

Force rewrite of all wrapper files, even if unchanged; defaults to False

Type:

bool

log_unknown_classes() None[source]

Log unwrapped classes.

parse_headers() None[source]

Parse the hpp files to collect C++ declarations.

Parse the headers with pygccxml and castxml to populate the source namespace with C++ declarations collected from the source tree.

discover_template_instantiations() None[source]

Discover explicit template instantiations from the source .cpp files.

CastXML only parses the header collection, so templated classes that are only explicitly instantiated in implementation files (template class Foo<2>;) are invisible to the main parse. For classes that opt in via discover_template_instantiations, find those explicit instantiations and populate the classes’ template args from them.

The template arguments are read primarily from the instantiation source text, which is independent of how a given CastXML version renders defaulted template arguments (e.g. CastXML 0.4.4 names an instantiation of AbstractMesh<2, 2> as AbstractMesh<2>). CastXML/pygccxml is used only as a fallback for macro-generated instantiations, which the text scan cannot see: just the files whose instantiation marker yielded no literal template class X<…>; are parsed (parsing every candidate file would re-derive what the text scan already found, at a full CastXML run each). The fallback map is merged into the discovered args; merging a defaulted-argument class this way is only safe with CastXML >= 0.6.0 (see PackageInfo.update_template_instantiations).

parse_package_info() None[source]

Parse the package info file to create a PackageInfo object.

write_header_collection() None[source]

Write the header collection to file.

write_wrappers() None[source]

Write the wrapper code for the package.

generate() None[source]

Parse yaml configuration and C++ source to generate Python wrappers.

Config model

Package information structure.

class cppwg.info.package_info.PackageInfo(name: str, package_config: dict[str, Any] | None = None)[source]

A structure to hold information about the package.

common_include_file

Use a common include file for all source files

Type:

bool

exceptions

C++ exception classes to translate into Python exceptions. Each entry is a class name, or a dict with a name and an optional message_method (the accessor for the message, defaulting to “what”). A pybind11 exception translator is generated automatically for each.

Type:

list[str | dict[str, str]]

exclude_default_args

Exclude default arguments from method wrappers.

Type:

bool

exclude_inherited_overrides

Skip emitting a binding for a method that overrides a virtual method already wrapped on a wrapped base class (pybind11 inheritance + virtual dispatch already expose it, so the derived binding is redundant). The virtual trampoline is still generated, so Python subclasses can override the method. Off by default.

Type:

bool

name

The name of the package

Type:

str

source_cpp_patterns

A list of implementation file patterns to scan for explicit template instantiations when discover_template_instantiations is enabled.

Type:

list[str]

source_hpp_patterns

A list of source file patterns to include

Type:

list[str]

typecasters

Type-caster headers to auto-include per class wrapper. Each entry is a dict with a header (the caster filename, e.g. caster_petsc.h) and a list of types (C++ type names it handles, e.g. [“Vec”, “Mat”]). When a class’s wrapped interface uses one of those types, cppwg adds the header to that class’s wrapper .cpp.

Type:

list[dict[str, Any]]

exception_info

Resolved exception translation data (cpp_type, message_expr, source_file), populated from exceptions after parsing the source.

Type:

list[dict[str, str]]

module_collection

A list of module info objects associated with this package

Type:

list[ModuleInfo]

source_cpp_files

A list of implementation file paths collected for template instantiation discovery. These are not added to the header collection.

Type:

list[str]

source_hpp_files

A list of source file names to include

Type:

list[str]

property parent: None

Returns None, as this is the top level of the info tree hierarchy.

add_module(module_info: ModuleInfo) None[source]

Add a module info object to the package.

Parameters:

module_info (ModuleInfo) – The module info object to add

init(restricted_paths: list[str]) None[source]

Initialise - collect header files and update info.

Note: implementation (.cpp) files are not collected here. They are only needed for template instantiation discovery, which walks the source tree for them lazily (see collect_source_cpp) to avoid a second tree walk on every run when discovery is not used.

Parameters:

restricted_paths (list[str]) – A list of restricted paths to skip when collecting header files.

collect_source_files(patterns: list[str], restricted_paths: list[str]) list[str][source]

Collect files matching the given patterns from the source root.

Walk through the source root and return any files matching the provided patterns e.g. *.hpp, skipping restricted paths and generated wrapper files (e.g. .cppwg.hpp). The result is sorted by filename, then by full path, giving a deterministic order even when a basename is shared.

Parameters:
  • patterns (list[str]) – A list of filename patterns to match e.g. ["*.hpp"].

  • restricted_paths (list[str]) – A list of restricted paths to skip when collecting files.

Returns:

The collected file paths, sorted by filename.

Return type:

list[str]

collect_source_headers(restricted_paths: list[str]) None[source]

Collect header files from the source root.

Walk through the source root and add any files matching the source file patterns e.g. *.hpp.

Parameters:

restricted_paths (list[str]) – A list of restricted paths to skip when collecting header files.

collect_source_cpp(restricted_paths: list[str]) None[source]

Collect implementation files from the source root.

Walk through the source root and add any files matching the source cpp patterns e.g. *.cpp. These are scanned for explicit template instantiations when discover_template_instantiations is enabled; they are not added to the header collection.

Parameters:

restricted_paths (list[str]) – A list of restricted paths to skip when collecting files.

update_from_source() None[source]

Update with data from the source headers.

uses_template_discovery() bool[source]

Check whether any wrapped class needs template instantiation discovery.

Discovery walks the source tree for the .cpp files and scans them, which is expensive, so it is only worth doing if at least one class has discovery enabled, does not already have its template arguments set (directly or via template_substitutions), and is actually templated - only a templated class can receive discovered template arguments. A class whose templated-ness cannot be determined (no resolved header path) is treated conservatively as possibly templated so discovery still runs.

Returns:

True if template instantiation discovery should be run.

Return type:

bool

update_template_instantiations(instantiation_map: dict[str, list[list[str]]], merge: bool = False, trust_defaulted_args: bool = True) None[source]

Populate class template args from discovered explicit instantiations.

Parameters:
  • instantiation_map (dict[str, list[list[str]]]) – Map of base class name to the discovered template arg lists, e.g. {“Foo”: [[“2”], [“3”]]}.

  • merge (bool) – If True, merge the arg lists into a class’s already discovery-discovered args (rather than only setting args for classes that have none). Used for the CastXML fallback so macro instantiations add to text-scanned ones. template_substitutions are never extended.

  • trust_defaulted_args (bool) – Whether the source of these arg lists renders defaulted trailing template arguments reliably (CastXML >= 0.6.0). When False, a merge is skipped for a class with defaulted template parameters to avoid adding a differently-rendered duplicate instantiation.

update_from_ns(source_ns: namespace_t) None[source]

Update modules with information from the parsed source namespace.

Parameters:

source_ns (pygccxml.declarations.namespace_t) – The source namespace

sort_classes() None[source]

Order each module’s classes so a base class precedes its subclasses.

Must run after base-class discovery and pruning, once every class’s declarations are final, so the inheritance ordering is complete.

discover_base_class_instantiations(source_ns: namespace_t) None[source]

Discover instantiations of opted-in templated classes from base classes.

A templated class that is never explicitly instantiated - e.g. an abstract base only ever used as a base class or through pointers - leaves no template class X<...>; for the source scan or the CastXML macro fallback to find. But it is implicitly instantiated wherever a wrapped concrete class derives from it, so it appears (at the right template arguments) among that class’s base declarations. Harvest those instantiations for any opted-in, still-unresolved templated class, so such bases can be wrapped without hand-written template_substitutions.

A harvested arg list is adopted only when its length matches the class’s template parameter count. This guards against a CastXML version that collapses a defaulted trailing argument (naming e.g. AbstractLinearPde<2, 2> as AbstractLinearPde<2>): the collapsed list is rejected and the class is left for template_substitutions.

Parameters:

source_ns (pygccxml.declarations.namespace_t) – The source namespace.

prune_uninstantiated_dependencies(restricted_paths: list[str]) None[source]

Drop wrapped instantiations that depend on an uninstantiated type.

A class instantiation only has linkable symbols if it is explicitly instantiated. Two things instantiate a project template: it being wrapped (each wrapped cpp_name is emitted as template class X; in the header collection) and an explicit template class X; in a source .cpp file. Their union is the set of instantiations that will have symbols.

If a wrapped method/constructor takes or returns a project template type (one sharing a base name with an instantiated class) that is not in that set - e.g. Facet<1>::GetFace returning the never-instantiated Facet<0> - the wrapper would fail to link/import, so that instantiation is dropped (per instantiation, so sibling instantiations of the same class survive) with a warning. Including source instantiations (not just wrapped ones) means a class curated out of wrapping but still instantiated in the source does not cause its wrapped siblings to be pruned.

Only members that would actually be wrapped are considered, applying the same config-driven exclusions the writers apply (excluded_methods, return_type_excludes, arg_type_excludes, constructor_arg_type_excludes, constructor_signature_excludes, calldef_excludes, and abstract-class constructors). A type reached only through an excluded method or constructor is never emitted and does not trigger a drop.

Library types (std::vector<double>, vtkSmartPointer<...>, …) do not share a base name with an instantiated class and are left alone. This is deliberately based on explicit instantiation rather than AST completeness: CastXML reports uninstantiated project templates as complete (it has the definition) and complete library templates as incomplete, so completeness is not a reliable signal.

Parameters:

restricted_paths (list[str]) – Paths to skip (e.g. the wrapper root) if the source .cpp files need to be collected to find explicit instantiations.

resolve_auto_includes() None[source]

Resolve project-type headers for classes with auto_includes enabled.

For each wrapped class that opts into auto_includes, inspect the types its wrapped methods/constructors actually expose (via _iter_wrapped_arg_return_types, so exclusions are honoured) plus the project types named as its template arguments (e.g. Foo<Bar, DIM>), resolve any that name a project class to that class’s header, and record the headers on class_info.auto_include_headers for the writer to emit. The class’s own header is dropped (the writer always includes it), as is anything that does not resolve to a project header (library types are left alone).

A class using common_include_file is skipped: the common header already includes every project header, so per-type includes are moot.

Must run after the wrapped set is final (post pruning/sorting) so the resolved headers reflect exactly what will be wrapped.

static parse_exception_entry(entry: Any) tuple[str, str][source]

Return the (class name, message method) for an exceptions config entry.

An entry may be a bare class name string, or a dict with a name and an optional message_method (defaulting to “what”).

Parameters:

entry (Any) – A single entry from the exceptions config list.

Returns:

The exception class name and the message accessor method name.

Return type:

tuple[str, str]

property exception_names: list[str]

Return the names of the configured exception classes.

property parsed_typecasters: list[tuple[str, list[str]]]

Return the validated typecasters as (header, types) tuples.

parse_typecaster_entry logs a warning for each malformed entry. Wrapper generation checks the typecasters for every class, so parsing per class would repeat those warnings once per class and drown out other output. Parse the config list once here (warning at most once per bad entry) and cache the result, so the class writers iterate an already-validated list.

Returns:

The validated (header, types) tuples, in config order.

Return type:

list[tuple[str, list[str]]]

static parse_typecaster_entry(entry: Any) tuple[str, list[str]] | None[source]

Return the (header, types) for a typecasters config entry, or None.

A valid entry is a dict with a non-empty string header and a types list of non-empty type-name strings, e.g. {“header”: “caster_petsc.h”, “types”: [“Vec”, “Mat”]}. The header is stripped of surrounding whitespace; each type is whitespace-normalized with utils.canonicalize_type_whitespace (the same normalization type_string_matches applies), so a padded value like “ Vec “ is stored as “Vec” and a blank type is dropped rather than kept as a never-matching entry (matching stays token- and case-sensitive). A malformed entry (not a dict, missing/blank header, or no usable types) is skipped with a warning rather than aborting generation.

Parameters:

entry (Any) – A single entry from the typecasters config list.

Returns:

The caster header filename and its list of type names, or None if the entry is malformed.

Return type:

tuple[str, list[str]] | None

resolve_exceptions(source_ns: namespace_t) None[source]

Resolve exception config entries into translation data.

For each entry in exceptions, look up the class in the source namespace, work out how to extract its message (calling the configured message_method, defaulting to what(), and adding .c_str() unless it already returns a pointer), and find which header declares it. The result is used to generate a pybind11 exception translator per module.

Parameters:

source_ns (pygccxml.declarations.namespace_t) – The source namespace

Module information structure.

class cppwg.info.module_info.ModuleInfo(name: str, module_config: dict[str, Any] | None = None)[source]

A structure to hold information for individual modules.

external_bases

Names of base classes that are wrapped in a different package (and so are unknown to this cppwg run) but are registered by one of the modules in imports. A class in this module may inherit from a class named here. This is the cross-package counterpart to base classes wrapped in another module of the same package, which are detected automatically. Listing a base here is required (and is the only way) to inherit from an externally-package-wrapped base, so that cppwg never emits a base class it cannot confirm is registered. Names are matched without template arguments, e.g. AbstractForce matches AbstractForce<2, 2>.

Type:

list[str]

imports

Python modules to import at the start of this generated module, e.g. the compiled module of another package or sibling module whose classes are used here as base classes. Importing them ensures those base types are registered with pybind11 before this module’s classes are registered. Setting this also enables referencing externally-wrapped base classes in class wrappers (see CppClassWrapperWriter), so that a class in this module can inherit from a class wrapped in another module (of this package, or of an imported package via external_bases). Do not list this module itself, to avoid a circular import.

Type:

list[str]

source_locations

A list of source locations for this module

Type:

list[str]

use_all_classes

Use all classes in the module

Type:

bool

use_all_free_functions

Use all free functions in the module

Type:

bool

use_all_variables

Use all variables in the module

Type:

bool

package_info

The package info object this module belongs to

Type:

PackageInfo

class_collection

A list of class info objects that belong to this module

Type:

list[CppClassInfo]

free_function_collection

A list of free function info objects that belong to this module

Type:

list[CppFreeFunctionInfo]

variable_collection

A list of variable info objects that belong to this module

Type:

list[CppVariableInfo]

property parent: PackageInfo

Returns the package info object that holds this module info object.

add_class(class_info: CppClassInfo) None[source]

Add a class info object to the module.

add_free_function(free_function_info: CppFreeFunctionInfo) None[source]

Add a free function info object to the module.

add_variable(variable_info: CppVariableInfo) None[source]

Add a variable info object to the module.

is_decl_in_source_path(decl: declaration_t) bool[source]

Check if the declaration is associated with a file in the specified source paths.

Parameters:

decl (declaration_t) – The declaration to check

Returns:

True if the declaration is associated with a file in a specified source path

Return type:

bool

sort_classes() None[source]

Order the class collection so each class comes after those it depends on.

pybind11 requires a base class to be registered before any subclass, so a class must be emitted after every class it extends. A class whose public method or constructor signatures use another wrapped class is ordered after it too, but only where that does not contradict the inheritance order (which would otherwise create a cycle).

The result is deterministic: it starts from an alphabetical baseline, breaks ties alphabetically, and matches base classes by name, so the registration order - and therefore the generated files - are stable from run to run. Requires the class decls/base_decls to be populated, so it must run after base-class discovery and pruning.

update_from_ns(source_ns: namespace_t) None[source]

Update module with information from the source namespace.

Parameters:

source_ns (pygccxml.declarations.namespace_t) – The source namespace

update_from_source(source_file_paths: list[str]) None[source]

Update module with information from the source headers.

Parameters:

source_files (list[str]) – A list of source file paths.

Class information structure.

class cppwg.info.class_info.CppClassInfo(name: str, class_config: dict[str, Any] | None = None)[source]

An information structure for individual C++ classes to be wrapped.

base_decls

Declarations for the base classes, one per template instantiation

Type:

pygccxml.declarations.declaration_t

cpp_names

The C++ names of the class e.g. [“Foo<2,2>”, “Foo<3,3>”]

Type:

list[str]

py_names

The Python names of the class e.g. [“Foo_2_2”, “Foo_3_3”]

Type:

list[str]

extract_templates_from_source() None[source]

Extract template args from the associated source file.

Search the source file for a class signature matching one of the template signatures defined in template_substitutions. If a match is found, set the corresponding template arg replacements for the class.

filter_discovered_instantiations(arg_lists: list[list[str]]) list[list[str]][source]

Drop discovered instantiations excluded by discover_arg_excludes.

discover_arg_excludes maps a template parameter name to the argument values to exclude for it, e.g. {"SPACE_DIM": [1]}. A discovered instantiation is dropped when the argument bound to a listed parameter is one of its excluded values. Matching by parameter name (rather than by position or by any argument) means a value that is a spatial dimension for one parameter but incidental for another - e.g. a trailing PROBLEM_DIM of 1 in Foo<2, 2, 1> - is only excluded where it is actually named. Only discovered instantiations are filtered; template_substitutions are wrapped as written.

A key may be given as either the bare parameter name (ELEMENT_DIM) or with a leading type, as template_substitutions signatures spell it (unsigned ELEMENT_DIM); both reduce to the same parameter name.

Parameters:

arg_lists (list[list[str]]) – Discovered template argument lists, e.g. [["1"], ["2"]].

Returns:

The arg lists with excluded instantiations removed. Returned unchanged when no exclusions apply or the parameter names cannot be recovered (so a filter is never applied blindly).

Return type:

list[list[str]]

template_params_from_source() list[str][source]

Return the class’s template parameter names from its header source.

Reads the class’s source file and extracts the parameter names from its template declaration e.g. [“ELEMENT_DIM”, “SPACE_DIM”] from template <unsigned ELEMENT_DIM, unsigned SPACE_DIM> class Foo.

Returns:

The template parameter names, or an empty list if the class has no source file or is not templated.

Return type:

list[str]

template_has_defaulted_params() bool[source]

Check whether the class’s header template declaration has a default.

e.g. True for template <unsigned A, unsigned B = A> class Foo. Used to decide whether a CastXML version that drops defaulted trailing arguments can be trusted for this class when merging fallback instantiations.

Returns:

True if the class is templated with at least one defaulted parameter.

Return type:

bool

apply_template_instantiations(instantiation_map: dict[str, list[list[str]]], merge: bool = False, trust_defaulted_args: bool = True) None[source]

Populate template args from explicit instantiations found in source.

If template instantiation discovery is enabled for this class and the map holds arg lists for its name, adopt them and rebuild the class names. template_substitutions (which sets template_arg_lists in extract_templates_from_source) takes precedence and is never extended.

Parameters:
  • instantiation_map (dict[str, list[list[str]]]) – Map of base class name to discovered template arg lists, e.g. {“Foo”: [[“2”], [“3”]]}.

  • merge (bool) – If True, merge the arg lists into args already discovered for this class (used for the CastXML fallback, so macro instantiations add to text-scanned ones) rather than only setting args when it has none.

  • trust_defaulted_args (bool) – Whether these arg lists render defaulted trailing template arguments reliably (CastXML >= 0.6.0). When False, a merge into a class with defaulted template parameters is skipped (with a warning) to avoid adding a differently-rendered duplicate of an existing instantiation.

extends(other: CppClassInfo) bool[source]

Check if the class extends the specified class.

Base classes are matched by name (unqualified, template arguments stripped) rather than by declaration identity: pygccxml may represent a base as a different declaration object than the one held by the wrapped class - e.g. after resolving a templated class via its typedef, or when the base instantiation is added later by base-class discovery - so an identity/equality match is unreliable.

Parameters:

other (CppClassInfo) – The other class to check

Returns:

True if the class extends the specified class, False otherwise

Return type:

bool

signature_arg_types() list[str][source]

Return the decl strings of class public method and constructor argument types.

Returns:

The argument type decl strings, e.g. ["Foo<2> const &", "double"].

Return type:

list[str]

requires(other: CppClassInfo) bool[source]

Check if the specified class is used in method signatures of this class.

Parameters:

other (CppClassInfo) – The specified class to check.

Returns:

True if the specified class is used in method signatures of this class.

Return type:

bool

update_from_ns(source_ns: namespace_t) None[source]

Update class with information from the source namespace.

Adds the class declarations and base class declarations.

Parameters:

source_ns (pygccxml.declarations.namespace_t) – The source namespace

update_from_source(source_file_paths: list[str]) None[source]

Update class with information from the source headers.

Parameters:

source_file_paths (list[str]) – A list of source file paths

py_name_base() str[source]

Return the shared Python-name base for the class, before template args.

This is the common prefix of every instantiation’s Python name (e.g. “Foo” for py_names [“Foo_2_2”, “Foo_3_3”]), and is used to name the single wrapper file shared by all of a class’s instantiations. For an untemplated class it is the (override) name unchanged; for a templated class it is cleaned the same way as the instantiation names.

update_py_names() None[source]

Set the Python names for the class, accounting for template args.

Set the name(s) of the class as it should appear in Python. This collapses template arguments, separates them by underscores, and removes special characters. There can be multiple names, one for each template class instantiation. For example, class “Foo” with template arguments [[2, 2], [3, 3]] will have a Python name list [“Foo_2_2”, “Foo_3_3”].

update_cpp_names() None[source]

Set the C++ names for the class, accounting for template args.

Set the name(s) of the class as it appears in C++. There can be multiple names, one for each template class instantiation. For example, a class “Foo” with template arguments [[2, 2], [3, 3]] will have a C++ name list [“Foo<2, 2>”, “Foo<3, 3>”].

update_names() None[source]

Update the C++ and Python names for the class.

Generic information structure.

class cppwg.info.base_info.BaseInfo(name: str, info_config: dict[str, Any] | None = None)[source]

A generic information structure for features.

Features include packages, modules, classes, free functions, etc. Information structures are used to store information about the features. BaseInfo is the base information structure, and set up attributes that are common to all features.

arg_type_excludes

Exclude any method, constructor or free function with an argument of one of these types. Patterns match a type as a whole token (so Node does not match AbstractNode).

Type:

list[str]

auto_includes

Automatically add #include`s for the project types a class’s wrapped method/constructor signatures use, when the class’s own header only forward-declares them (so the wrapper still compiles without listing them by hand under `source_includes). Only project types - classes defined under the module source_locations - are resolved; library types are left alone. None (the default) means inherit from further up the info tree, where it is treated as off (opt-in); set it to True or False at any level (package, module or class). Has no effect with common_include_file (the common header already includes everything).

Type:

bool | None

calldef_excludes

Deprecated: use arg_type_excludes and/or return_type_excludes. Kept for backwards compatibility; treated as both arg_type_excludes and return_type_excludes.

Type:

list[str]

constructor_arg_type_excludes

Exclude constructors (only) with an argument of one of these types, for the case where a type should be excluded from constructors but not methods. Matched the same way as arg_type_excludes.

Type:

list[str]

constructor_signature_excludes

List of exclude patterns for constructor signatures.

Type:

list[list[str]]

custom_generator

A custom generator for the feature.

Type:

str

discover_arg_excludes

Drop a discovered template instantiation when the argument bound to a named template parameter is one of the listed values, e.g. {SPACE_DIM: [1]} drops Foo<SPACE_DIM=1> but keeps Foo<SPACE_DIM=2>. Matching is by parameter name, so a value that is spatial for one parameter but incidental for another - e.g. a trailing PROBLEM_DIM of 1 in Bar<2, 2, 1> - is only excluded where it is actually named. Only instantiations found by discovery are filtered; template_substitutions are wrapped as written. Set at any level (package, module or class); it inherits down the info tree.

Type:

dict[str, list]

discover_template_instantiations

Discover template instantiations for templated classes automatically by scanning the C++ source files (see PackageInfo.source_cpp_patterns) for explicit instantiations e.g. template class Foo<2>;. Used as a fallback to populate template arguments when no template_substitutions matched. None (the default) means inherit from further up the info tree; set it to True or False at any level (package, module or class).

Type:

bool | None

excluded

Exclude this feature.

Type:

bool

excluded_methods

Do not include these methods.

Type:

list[str]

excluded_variables

Do not include these variables.

Type:

list[str]

name

The name of the package, module, class etc. represented by this object.

Type:

str

name_replacements

A dictionary of name replacements e.g. {“double”:”Double”}

Type:

dict[str, str]

pointer_call_policy

The default pointer call policy.

Type:

str

prefix_code

Custom wrapper code that comes before the auto-generated feature code.

Type:

list[str]

prefix_text

Text to add at the top of all wrappers.

Type:

str

reference_call_policy

The default reference call policy.

Type:

str

return_type_excludes

Exclude any method or free function returning one of these types. Matched the same way as arg_type_excludes.

Type:

list[str]

smart_ptr_type

Handle classes with this smart pointer type.

Type:

str

source_includes

A list of source files to be included with the feature.

Type:

list[str]

source_root

The root directory of the C++ source code.

Type:

str

suffix_code

Custom wrapper code that comes after the auto-generated feature code.

Type:

list[str]

template_substitutions

A list of template substitution sequences.

Type:

list[dict[str, Any]]

custom_generator_instance

An instance of the custom generator class, or None if not set.

Type:

cppwg.templates.custom.Custom | None

abstract property parent: BaseInfo | None

Returns this object’s parent node in the info tree hierarchy.

This property is supplied by subclasses e.g. a ModuleInfo’s parent is a PackageInfo, a CppClassInfo’s parent is a ModuleInfo etc.

Returns:

The parent node in the info tree hierarchy.

Return type:

BaseInfo | None

load_custom_generator() None[source]

Check if a custom generator is specified and load it.

hierarchy_attribute(attribute_name: str) Any[source]

Get the attribute value from this object or one further up the info tree.

Ascend the info tree hierarchy searching for the attribute and return the first value found for it.

Parameters:

attribute_name (str) – The attribute name to search for.

Returns:

The attribute value, or None if not found.

Return type:

Any

hierarchy_attribute_gather(attribute_name: str) list[Any][source]

Get a list of attribute values from this object and others in the info tree.

Ascend the info tree hierarchy searching for the attribute and return a list of all the values found for it.

Parameters:

attribute_name (str) – The attribute name to search for.

Returns:

The list of attribute values.

Return type:

list[Any]

hierarchy_attribute_gather_flat(attribute_name: str) list[Any][source]

Gather a list-valued attribute across the info tree, flattened one level.

hierarchy_attribute_gather returns one entry per hierarchy level that defines the attribute; for a list-valued option each entry is itself a list. This flattens those into a single list of the option’s items across all levels (e.g. all exclude patterns from class, module and package).

Only actual sequences (list/tuple/set) are flattened; any other value (e.g. a yaml option: foo written instead of the expected option: [foo]) is treated as a single item rather than being iterated - which for a str would split it into individual characters.

Parameters:

attribute_name (str) – The attribute name to search for.

Returns:

The flattened list of items.

Return type:

list[Any]

Parsers

Parser for input yaml.

class cppwg.parsers.package_info_parser.PackageInfoParser(config_file: str, source_root: str)[source]

Parser for the package info yaml file.

config_file

The path to the package info yaml config file

Type:

str

source_root

The root directory of the C++ source code

Type:

str

parse() PackageInfo[source]

Parse the yaml file.

Parse the package info yaml file to extract information about the package, modules, classes, and free functions.

Returns:

The object holding data from the parsed package info yaml file.

Return type:

PackageInfo

warn_deprecated_options(raw_config: Any) None[source]

Emit a one-time warning for each deprecated option in the raw config.

Recursively scans the loaded yaml (which nests modules, classes, free functions and variables) for deprecated option keys and logs a warning once per key found.

Parameters:

raw_config (Any) – The raw parsed yaml structure.

convert_custom_generator(config: dict[str, Any]) None[source]

Convert the custom generator path to a full path if set in the config.

Parameters:

config (dict[str, Any]) – The config dictionary.

convert_path(raw_path: str) str[source]

Convert a path which has a CPPWG_SOURCEROOT_STRING placeholder.

Parameters:

raw_path (str) – The path to convert.

full_path(relative_path: str) str[source]

Get the full path for a path specified relative to the source root.

Parameters:

relative_path (str) – The path relative to the source root.

verify_path(path: str) None[source]

Verify that the path exists if set.

Parameters:

path (str) – The path.

Parser for C++ source code.

class cppwg.parsers.source_parser.CppSourceParser(source_root: str, wrapper_header_collection: str, castxml_binary: str, source_includes: list[str], castxml_cflags: str = '', castxml_compiler: str = None)[source]

Parser for C++ source code.

castxml_cflags

Optional cflags to be passed to CastXML e.g. “-std=c++17”

Type:

str

castxml_compiler

Optional compiler path to be passed to CastXML

Type:

str

castxml_binary

The path to the CastXML binary

Type:

str

source_includes

The list of source include paths

Type:

list[str]

source_root

The root directory of the source code

Type:

str

wrapper_header_collection

The path to the header collection file

Type:

str

xml_generator_config() pygccxml.parser.xml_generator_configuration_t[source]

Build the CastXML configuration for parsing.

Returns:

The XML generator configuration.

Return type:

parser.xml_generator_configuration_t

parse() pygccxml.declarations.namespace.namespace_t[source]

Parse the C++ source code from the header collection using CastXML and pygccxml.

Returns:

The namespace containing C++ declarations from the source tree

Return type:

namespace_t

parse_instantiations(source_files: list[str]) dict[str, list[list[str]]][source]

Find explicit template instantiations in the given source files.

CastXML only sees the template definitions in the headers, not the explicit instantiations (e.g. template class Foo<2>;) that live in the implementation files. This parses each implementation file and collects the template class instantiations it defines, returning a map of base class name to the template argument lists found.

Only instantiations located in the parsed file itself are kept (i.e. the explicit instantiations), not the many implicit instantiations pulled in from included headers. Files that fail to parse are skipped with a warning, so discovery is best-effort and never fatal to generation.

Parameters:

source_files (list[str]) – The implementation files (typically .cpp) to scan.

Returns:

Map of base class name to discovered template arg lists, e.g. {“Foo”: [[“2”], [“3”]], “AbstractMesh”: [[“2”, “2”]]}.

Return type:

dict[str, list[list[str]]]

Writers

Wrapper code writer for C++ classes.

class cppwg.writers.class_writer.CppClassWrapperWriter(class_info: CppClassInfo, wrapper_templates: dict[str, Template], module_classes: dict[class_t, str], package_classes: set[class_t] = None, overwrite: bool = False, package_class_infos: dict[class_t, CppClassInfo] = None)[source]

Writer to generate wrapper code for C++ classes.

class_info

The class information

Type:

CppClassInfo

wrapper_templates

Templates with placeholders for generating wrapper code

Type:

dict[str, Template]

module_classes

A dictionary of decls and names for all classes in the module

Type:

dict[pygccxml.declarations.class_t, str]

package_classes

Decls for every class wrapped anywhere in the package (all modules). Used to detect base classes wrapped in another module of this package.

Type:

set[pygccxml.declarations.class_t]

package_class_infos

Maps each wrapped decl to its class_info. Used by the inherited-override skip to consult a base class’s excluded_methods.

Type:

dict[pygccxml.declarations.class_t, CppClassInfo]

overwrite

Force rewrite of the class wrapper files, even if unchanged

Type:

bool

hpp_string

The hpp wrapper code

Type:

str

cpp_string

The cpp wrapper code

Type:

str

prefix_block() str[source]

Return the prefix text block for the top of a wrapper file.

Returns:

The prefix text followed by a newline, or an empty string.

Return type:

str

includes_block() str[source]

Return the #include block for a class wrapper cpp file.

Returns:

The include directives, one per line.

Return type:

str

smart_ptr_handle() str[source]

Return the smart pointer holder declaration, or an empty string.

Returns:

e.g. “PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>)”.

Return type:

str

prefix_code() str[source]

Return any custom prefix code lines for the class.

suffix_code() str[source]

Return any custom suffix code lines for the class.

virtual_overrides(template_idx: int) tuple[str, str, list[member_function_t]][source]

Build the virtual “trampoline” override block for the class.

Identify any methods needing overrides (i.e. any that are virtual in the current class or in a base class), and build the trampoline override class that forwards them to Python.

Parameters:

template_idx (int) – The index of the template in the class info

Returns:

The return-type typedef block, the override class block (empty if the class has no virtual methods), and the list of methods needing an override.

Return type:

tuple[str, str, list[pygccxml.declarations.member_function_t]]

bases_block(class_decl: class_t) str[source]

Return the base-class list appended to the py::class_ declaration.

Cross-module inheritance is opted into per module via imports. When set, a base class that is not wrapped in this module may still be referenced, but only if it is known to be registered elsewhere: either it is wrapped in another module of this package, or the user has listed it under external_bases (for bases wrapped in an imported package). This avoids emitting unregistered bases (e.g. framework/utility bases), which would fail at import.

Parameters:

class_decl (pygccxml.declarations.class_t) – The class declaration whose bases to inspect.

Returns:

e.g. “, AbstractFoo, InterfaceFoo”.

Return type:

str

build_hpp(register_py_names: list[str]) str[source]

Build the class wrapper hpp file contents.

One hpp is emitted per class, forward-declaring the register function for every instantiation that is written.

Parameters:

register_py_names (list[str]) – The Python names of the instantiations that have a register function, e.g. [“Foo_2_2”, “Foo_3_3”].

Returns:

The hpp wrapper code.

Return type:

str

build_cpp_header(class_typedefs: str = '', return_typedefs: str = '') str[source]

Build the shared preamble of the class wrapper cpp file.

Emitted once per class (not per instantiation): the includes, the smart pointer holder declaration, class-level prefix code, the per-instantiation alias typedefs, and the deduplicated trampoline return typedefs.

Parameters:
  • class_typedefs (str) – The alias typedefs (typedef <cpp> <py>;) for every instantiation in the file, emitted ahead of the registration blocks so any block can refer to any instantiation by its alias.

  • return_typedefs (str) – The trampoline return typedefs, deduplicated across instantiations.

Returns:

The cpp preamble.

Return type:

str

build_class_register(template_idx: int) tuple[str, str][source]

Build the registration block for one template instantiation.

Parameters:

template_idx (int) – The index of the template instantiation in the class info.

Returns:

The registration block and its trampoline return typedefs (the latter are hoisted into the shared preamble and deduplicated).

Return type:

tuple[str, str]

build_struct_enum_register(template_idx: int) str[source]

Build the registration block for a struct-enum instantiation.

Handles a struct that wraps a single nested enum, for example:

struct Foo {
  enum Value {A, B, C};
};
Parameters:

template_idx (int) – The index of the template instantiation in the class info.

Returns:

The registration block.

Return type:

str

write(work_dir: str) None[source]

Write the hpp and cpp wrapper code to file.

All of a class’s template instantiations share a single {class}.cppwg.hpp / .cpp pair. The cpp holds one shared preamble followed by one registration block per instantiation.

Parameters:

work_dir (str) – The directory to write the files to

write_files(work_dir: str, file_stem: str) None[source]

Write the hpp and cpp wrapper code to file.

Parameters:
  • work_dir (str) – The directory to write the files to

  • file_stem (str) – The wrapper file stem shared by all of the class’s instantiations, e.g. Foo (for Foo.cppwg.hpp / Foo.cppwg.cpp).

Wrapper code writer for C++ methods.

class cppwg.writers.method_writer.CppMethodWrapperWriter(class_info: CppClassInfo, template_idx: int, method_decl: member_function_t, wrapper_templates: dict[str, Template])[source]

Manage addition of method wrapper code.

class_info

The class information for the class containing the method

Type:

CppClassInfo

template_idx

The index of the template in class_info

Type:

int

method_decl

The pygccxml declaration object for the method

Type:

[pygccxml.declarations.member_function_t]

class_decl

The class declaration for the class containing the method

Type:

[pygccxml.declarations.class_t]

wrapper_templates

Templates with placeholders for generating wrapper code

Type:

dict[str, Template]

class_py_name

The Python name of the class e.g. ‘Foo_2_2’

Type:

str | None

template_params

The template params for the class e.g. [‘DIM_A’, ‘DIM_B’]

Type:

list[str] | None

template_args

The template args for the class e.g. [‘2’, ‘2’]

Type:

list[str] | None

exclude() bool[source]

Check if the method should be excluded from the wrapper code.

Returns:

True if the method should be excluded, False otherwise

Return type:

bool

static method_is_excluded(class_info: CppClassInfo, class_decl: class_t, method_decl: member_function_t) bool[source]

Return True if a method would be excluded from the wrapper code.

The per-instance exclude() delegates here so the same decision can be reused without a writer. The inherited-override overload-shadowing guard (see class_writer._is_inherited_override) needs it: a sibling overload that is excluded emits no binding, so it cannot shadow an inherited base overload set and must not block skipping a redundant override.

Parameters:
  • class_info (CppClassInfo) – The info for the class containing the method.

  • class_decl (pygccxml.declarations.class_t) – The declaration of the class the method is being wrapped on.

  • method_decl (pygccxml.declarations.member_function_t) – The candidate method.

Returns:

True if the method should be excluded, False otherwise.

Return type:

bool

generate_wrapper() str[source]

Generate the method wrapper code.

Example output:

.def("bar", (void(Foo::*)(double)) &Foo::bar, " ", py::arg("d") = 1.0)
Returns:

The method wrapper code.

Return type:

str

generate_virtual_override_wrapper() str[source]

Generate wrapper code for overriding virtual methods.

Example output:

void bar(double d) const override {
    PYBIND11_OVERRIDE_PURE(
        bar,
        Foo_2_2,
        bar,
        d);
}
Returns:

The virtual override wrapper code.

Return type:

str

Wrapper code writer for C++ class constructors.

class cppwg.writers.constructor_writer.CppConstructorWrapperWriter(class_info: CppClassInfo, template_idx: int, ctor_decl: constructor_t, wrapper_templates: dict[str, Template])[source]

Manage addition of constructor wrapper code.

class_info

The class information for the class containing the constructor

Type:

CppClassInfo

template_idx

The index of the template in class_info

Type:

int

ctor_decl

The pygccxml declaration object for the constructor

Type:

pygccxml.declarations.constructor_t

class_decl

The class declaration for the class containing the constructor

Type:

pygccxml.declarations.class_t

wrapper_templates

Templates with placeholders for generating wrapper code

Type:

dict[str, Template]

class_py_name

The Python name of the class e.g. ‘Foo_2_2’

Type:

str | None

template_params

The template params for the class e.g. [‘DIM_A’, ‘DIM_B’]

Type:

list[str] | None

template_args

The template args for the class e.g. [‘2’, ‘2’]

Type:

list[str] | None

exclude() bool[source]

Check if the constructor should be excluded from the wrapper code.

Returns:

True if the constructor should be excluded, False otherwise

Return type:

bool

generate_wrapper() str[source]

Generate the constructor wrapper code.

Example output: .def(py::init<int, bool >(), py::arg(“i”) = 1, py::arg(“b”) = false)

Returns:

The constructor wrapper code.

Return type:

str

Wrapper code writer for modules.

class cppwg.writers.module_writer.CppModuleWrapperWriter(module_info: ModuleInfo, wrapper_templates: dict[str, Template], wrapper_root: str, overwrite: bool = False)[source]

Class to automatically generates Python bindings for modules.

A module is a collection of classes and free functions that are to be wrapped in Python. The module writer generates the main cpp file for the module, which contains the pybind11 module definition. Within the module definition, the module’s free functions and classes are registered.

module_info

The module information to generate Python bindings for

Type:

ModuleInfo

wrapper_templates

Templates with placeholders for generating wrapper code

Type:

dict[str, Template]

wrapper_root

The output directory for the generated wrapper code

Type:

str

overwrite

Force rewrite of all wrapper files, even if unchanged

Type:

bool

classes

A dictionary of decls and names for all classes to be wrapped in the module

Type:

dict[pygccxml.declarations.class_t, str]

generate_exception_translator() str[source]

Generate a pybind11 exception translator for the package’s exceptions.

Produces a py::register_exception_translator call with a catch clause for each configured exception class, mapping it to a Python RuntimeError. Returns an empty string if no exceptions are configured.

Returns:

The exception translator code, indented for the module body.

Return type:

str

property full_module_name: str

Return the pybind11 module name, e.g. _packagename_modulename.

build_module_context() dict[str, str][source]

Build the substitution blocks for the module’s main cpp template.

Each value is a fully-formed string block (including its own trailing newlines, or empty) that is dropped into the module_main_cpp template. All the iteration and conditional logic lives here; the template only places the resulting blocks.

Returns:

A mapping of template placeholder names to code blocks.

Return type:

dict[str, str]

write_module_wrapper() None[source]

Generate the contents of the main cpp file for the module.

The main cpp file is named _packagename_modulename.main.cppwg.cpp. This file contains the pybind11 module definition, within which the module’s classes and free functions are registered.

Example output:

#include <pybind11/pybind11.h>
#include "Foo.cppwg.hpp"
#include "Bar.cppwg.hpp"

PYBIND11_MODULE(_packagename_modulename, m)
{
    register_Foo_class(m);
    register_Bar_class(m);
}
write_class_wrappers() None[source]

Write wrappers for classes in the module.

write() None[source]

Generate the module and class wrappers.

Custom generators

class cppwg.templates.custom.Custom[source]

This class returns custom code snippets for use during the wrapper generation processes. It can be used as a base class for custom code generators.

get_class_cpp_pre_code(*args, **kwargs) str[source]

Return a string of C++ code to be inserted before the class definition.

get_class_cpp_def_code(*args, **kwargs) str[source]

Return a string of C++ code to be inserted in the class definition.

get_source_includes(*args, **kwargs) list[source]

Return headers to add to the #include block of the class wrapper.

Use this for headers the generated code needs but that cppwg cannot infer from the parsed C++ signatures - e.g. types named only inside the get_class_cpp_def_code() output, which auto-include detection never sees. Each entry is spelled as under source_includes: a bare name (Foo.hpp) becomes a quoted include (#include “Foo.hpp”) and an angle-bracket form (<foo>) becomes a system include (#include <foo>). cppwg adds the quotes, so do not wrap the name in quotes yourself. Returns an empty list by default.

get_module_pre_code() str[source]

Return a string of C++ code to be inserted before the module definition.

get_module_code() str[source]

Return a string of C++ code to be inserted in the module definition.