scikit_build_core.settings package

Submodules

scikit_build_core.settings.auto_cmake_version module

scikit_build_core.settings.auto_cmake_version.find_min_cmake_version(cmake_content)[source]

Locate the minimum required version. Return None if not found.

Return type:

str | None

scikit_build_core.settings.auto_requires module

scikit_build_core.settings.auto_requires.get_min_requires(package, reqlist)[source]

Read the build requirements from a pyproject.toml file and return the minimum version required for the given package. Returns None if no minimum version is discovered.

Return type:

Version | None

scikit_build_core.settings.documentation module

scikit_build_core.settings.documentation.pull_docs(dc)[source]

Pulls documentation from a dataclass.

Return type:

dict[str, str]

scikit_build_core.settings.json_schema module

exception scikit_build_core.settings.json_schema.FailedConversionError[source]

Bases: TypeError

scikit_build_core.settings.json_schema.convert_type(t, *, normalize_keys)[source]
Return type:

dict[str, Any]

scikit_build_core.settings.json_schema.to_json_schema(dclass, *, normalize_keys)[source]
Return type:

dict[str, Any]

scikit_build_core.settings.skbuild_docs_readme module

scikit_build_core.settings.skbuild_docs_readme.mk_skbuild_docs()[source]

Makes documentation for the skbuild model.

Return type:

str

scikit_build_core.settings.skbuild_docs_sphinx module

Make documentation for the skbuild model in sphinx format.

scikit_build_core.settings.skbuild_docs_sphinx.mk_skbuild_docs()[source]
Return type:

str

scikit_build_core.settings.skbuild_model module

class scikit_build_core.settings.skbuild_model.BackportSettings(find_python=<Version('3.26.1')>)[source]

Bases: object

find_python: Version = <Version('3.26.1')>

If CMake is less than this value, backport a copy of FindPython.

Set to 0 or an empty string to disable this.

class scikit_build_core.settings.skbuild_model.BuildSettings(tool_args=<factory>, targets=<factory>, verbose=False, requires=<factory>)[source]

Bases: object

requires: List[str]

Additional build-system.requires.

Intended to be used in combination with overrides.

targets: List[str]

The build targets to use when building the project.

If not specified or an empty list, the default target is used.

tool_args: List[str]

Extra args to pass directly to the builder in the build step.

verbose: bool = False

Verbose printout when building.

Equivalent to CMAKE_VERBOSE_MAKEFILE.

class scikit_build_core.settings.skbuild_model.CMakeSettings(minimum_version=None, version=None, args=<factory>, define=<factory>, verbose=None, build_type='Release', source_dir=PosixPath('.'), targets=None, toolchain_file=None, python_hints=True)[source]

Bases: object

args: List[str]

A list of args to pass to CMake when configuring the project.

Setting this in config or envvar will override toml.

See also

cmake.define

build_type: str | List[str] = 'Release'

The build type to use when building the project.

Pre-defined CMake options are: Debug, Release, RelWithDebInfo, MinSizeRel

Custom values can also be used.

A list of build types can be given to build and install more than one configuration into the same wheel: ["Release", "Debug"] in TOML, a repeated -Ccmake.build-type=... config-setting, or Release;Debug as an environment variable. Single-config generators (Ninja, Makefiles) are reconfigured in place for each extra build type; multi-config generators (Visual Studio, Xcode, Ninja Multi-Config) build each --config. Every build type is installed to the same prefix, so use CMAKE_<CONFIG>_POSTFIX to avoid clobbering files between configurations.

Changed in version 1.0: A list of build types can now be given.

define: Annotated[Dict[str, CMakeSettingsDefine], 'EnvVar']

A table of defines to pass to CMake when configuring the project. Additive.

minimum_version: Version | None = None

DEPRECATED in 0.8; use version instead.

python_hints: bool = True

Do not pass the current environment’s python hints such as Python_EXECUTABLE. Primarily used for cross-compilation where the CMAKE_TOOLCHAIN_FILE should handle it instead.

source_dir: Path = PosixPath('.')

The source directory to use when building the project.

Currently only affects the native builder (not the setuptools plugin).

targets: List[str] | None = None

DEPRECATED in 0.10; use build.targets instead.

toolchain_file: Path | None = None

The CMAKE_TOOLCHAIN_FILE / –toolchain used for cross-compilation.

This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

verbose: bool | None = None

DEPRECATED in 0.10, use build.verbose instead.

version: SpecifierSet | None = None

The versions of CMake to allow as a python-compatible specifier.

If CMake is not present on the system or does not pass this specifier, it will be downloaded via PyPI if possible with the equivalent specifier used.

An empty string will disable this check.

Special cases:
  • On scikit-build-core 0.10+ CMakeLists.txt is the default value otherwise it’s >=3.15.

  • If CMakeLists.txt is passed, the cmake_minimum_required is read from the CMakeLists.txt file, using that as the minimum specifier. If the file fails to read, >=3.15 is used instead.

See also

ninja.version

class scikit_build_core.settings.skbuild_model.CMakeSettingsDefine(raw: str | bool | List[str])[source]

Bases: str

A str subtype for automatically normalizing bool and list values to the CMake representation in the cmake.define settings key.

json_schema = str | bool | typing.List[str]
class scikit_build_core.settings.skbuild_model.EditableSettings(mode='redirect', verbose=True, rebuild=False, rebuild_dir='')[source]

Bases: object

mode: Literal['redirect', 'inplace'] = 'redirect'

Select the editable mode to use. Can be “redirect” (default) or “inplace”.

rebuild: bool = False

Rebuild the project when the package is imported.

build-dir must be set, except in inplace mode (where the source directory is the build directory).

rebuild_dir: str = ''

Install rebuildable editables into this tree (a newer alternative to editable.rebuild).

Setting this turns on rebuild-on-import by itself; the editable.rebuild flag is ignored when it is set. The compiled artifacts are installed here at first build and re-installed in place on every import-triggered rebuild, and the redirect references them by absolute path. Must be an absolute (or source-relative) path that is stable between build and run time, and supports the same template substitutions as build-dir. This relocates only the install tree; build-dir is still required and still hosts the CMake build that the rebuild re-runs.

The tree is wiped and recreated on each build, so it must be a fresh or scikit-build-core-managed directory – pointing it at a populated directory such as your source tree is refused to avoid deleting those files. A managed tree gets a CACHEDIR.TAG and a .gitignore so its compiled artifacts stay out of backups and version control.

Added in version 1.0.

property rebuild_enabled: bool

True when rebuild-on-import is active.

Setting rebuild-dir turns this on by itself, so the rebuild flag is ignored when it is set.

verbose: bool = True

Turn on verbose output for the editable mode rebuilds.

class scikit_build_core.settings.skbuild_model.EnvValue(raw)[source]

Bases: object

A single entry in the top-level env table.

Accepts either a literal string or a table with env / default / force keys. Resolution against the build environment is deferred to resolve() so that the force flag survives parsing (unlike the cmake.define EnvVar form, which resolves at parse time). A bare string is shorthand for { default = "<string>" }.

default: str | None
env: str | None
force: bool
resolve(env)[source]

Resolve to the final string value (or None if unset) against env.

env (if set) is looked up in the environment with default as the fallback. None means “leave the variable unset”.

Return type:

str | None

class scikit_build_core.settings.skbuild_model.GenerateSettings(path, template='', template_path=None, location='install')[source]

Bases: object

location: Literal['install', 'build', 'source'] = 'install'

The place to put the generated file.

The build directory is useful for CMake files, and the install directory is useful for Python files, usually. You can also write directly to the source directory, will overwrite existing files & remember to gitignore the file.

path: Path

The path (relative to platlib) for the file to generate.

template: str = ''

The template string to use for the file.

Template style placeholders are available for all the metadata.

Either this or generate[].template-path must be set.

template_path: Path | None = None

The path to the template file. If empty, a template must be set.

Either this or generate[].template must be set.

class scikit_build_core.settings.skbuild_model.InstallSettings(components=<factory>, targets=<factory>, strip=None)[source]

Bases: object

components: List[str]

The components to install.

If not specified or an empty list, all default components are installed.

strip: bool | None = None

Whether to strip the binaries.

Equivalent to --strip in cmake install.

True for release builds (Release or MinSizeRel) on scikit-build-core 0.5+.

Note

0.5-0.10.5 also incorrectly set this for debug builds.

targets: List[str]

Build targets to run during the install step via cmake --build --target.

This is intended for projects that group their install rules under an umbrella “distribution” build target (such as LLVM’s install-distribution) rather than using CMake install COMPONENTs. Each listed target is built, which triggers its install rules into the staging prefix.

This relies on the configure-time CMAKE_INSTALL_PREFIX (set automatically by scikit-build-core to the wheel staging directory); the --strip and --component options of cmake --install do not apply to these targets. components and targets may be combined; both will run.

Added in version 1.0.

class scikit_build_core.settings.skbuild_model.LoggingSettings(level='WARNING')[source]

Bases: object

level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 'WARNING'

The logging level to display.

class scikit_build_core.settings.skbuild_model.MessagesSettings(after_failure='', after_success='')[source]

Bases: object

Settings for messages.

after_failure: str = ''

A message to print after a build failure.

after_success: str = ''

A message to print after a successful build.

class scikit_build_core.settings.skbuild_model.NinjaSettings(minimum_version=None, version=<SpecifierSet('>=1.5')>, make_fallback=True)[source]

Bases: object

make_fallback: bool = True

Use Make as a fallback if a suitable Ninja executable is not found.

If Make is also not available on the system, a ninja dependency is added to the build-system.requires according to ninja.version.

See also

ninja.version

minimum_version: Version | None = None

DEPRECATED in 0.8; use version instead.

version: SpecifierSet = <SpecifierSet('>=1.5')>

The versions of Ninja to allow.

If Ninja is not present on the system or does not pass this specifier, it will be downloaded via PyPI if possible with the equivalent specifier used.

An empty string will disable this check.

class scikit_build_core.settings.skbuild_model.SDistSettings(include=<factory>, exclude=<factory>, inclusion_mode=None, reproducible=True, cmake=False, force_include=<factory>, resolve_symlinks=None)[source]

Bases: object

cmake: bool = False

If set to True, CMake will be run before building the SDist.

exclude: List[str]

Files to exclude from the SDist even if they are included by default. Supports gitignore syntax.

See also

sdist.include

force_include: Dict[str, str]

Force-include files into the SDist.

Maps source paths to destinations relative to the SDist root. Keys are relative to the project root; they may point outside it (e.g. ../shared) or be absolute, and ~ is expanded. A source may be a file or a directory; directories are copied recursively, skipping VCS and __pycache__ junk.

Force-included files override files at the same destination. A missing source is an error.

A force-included file is forced in even if sdist.exclude matches its destination, since naming an exact source is an explicit request. A force-included directory stays subject to sdist.exclude, so a bulk copy can still be trimmed by an exclude pattern.

Added in version 1.0.

include: List[str]

Files to include in the SDist even if they are skipped by default. Supports gitignore syntax.

Always takes precedence over sdist.exclude

See also

sdist.exclude

inclusion_mode: Literal['classic', 'default', 'manual', 'explicit'] | None = None

Method to use to compute the files to include and exclude.

The methods are:

  • “default”: Process the git ignore files. Shortcuts on ignored directories.

  • “classic”: The behavior before 0.12, like “default” but does not shortcut directories.

  • “manual”: No extra logic, based on include/exclude only.

  • “explicit”: Opt-in only. Nothing is included unless it matches an include pattern, and exclude is applied after, so it can trim included files back out. Like “manual”, git ignore files are not read.

If you don’t set this, it will be “default” unless you set the minimum version below 0.12, in which case it will be “classic”.

Added in version 0.12.

Changed in version 1.0: Added the “explicit” mode.

reproducible: bool = True

Try to build a reproducible distribution.

Unix and Python 3.9+ recommended.

SOURCE_DATE_EPOCH will be used for timestamps, or a fixed value if not set.

Which symlinks to resolve in the SDist, storing the target’s contents instead.

The modes are:

  • “all”: Resolve every symlink, copying its target’s contents.

  • “external”: Resolve only symlinks that point outside the project (those would be broken once the SDist is extracted); store symlinks that stay inside the project as-is.

  • “none”: Store every symlink as-is, including directory symlinks.

  • “classic”: Store file symlinks as-is, but follow directory symlinks, copying their contents (scikit-build-core 0.x behavior).

A symlink that can’t be resolved (dangling, or a directory symlink loop) is stored as a symlink in every mode, with a warning if it was supposed to be resolved.

If you don’t set this, it will be “all” unless you set the minimum version below 1.0, in which case it will be “classic” to preserve backward compatibility.

Added in version 1.0.

class scikit_build_core.settings.skbuild_model.ScikitBuildSettings(cmake=<factory>, ninja=<factory>, logging=<factory>, sdist=<factory>, wheel=<factory>, backport=<factory>, editable=<factory>, build=<factory>, install=<factory>, generate=<factory>, messages=<factory>, search=<factory>, metadata=<factory>, env=<factory>, strict_config=True, experimental=False, variant=<factory>, variant_name=<factory>, variant_label=None, null_variant=False, minimum_version=None, build_dir='', fail=None)[source]

Bases: object

backport: BackportSettings
build: BuildSettings
build_dir: str = ''

The CMake build directory. Defaults to a unique temporary directory.

This can be set to reuse the build directory from previous runs.

cmake: CMakeSettings
editable: EditableSettings
env: Annotated[Dict[str, EnvValue], 'EnvTable']

A table of environment variables to set for the CMake subprocesses.

Applied to the configure, build, and install steps. A variable is only set if not already present (like a setdefault); pass force = true to overwrite. Each value is a literal string or a table with env (read from another environment variable), default, and force; an entry that resolves to nothing is skipped. Independent of the if.env override condition.

Added in version 1.0.

experimental: bool = False

Enable early previews of features not finalized yet.

fail: bool | None = None

Immediately fail the build. This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

generate: List[GenerateSettings]
install: InstallSettings
logging: LoggingSettings
messages: MessagesSettings
metadata: Dict[str, Dict[str, Any]]

List dynamic metadata fields and hook locations in this table.

minimum_version: Version | None = None

If set, this will provide a method for backward compatibility.

ninja: NinjaSettings
null_variant: bool = False

Experimental PEP 817 null-variant selector.

This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

Added in version 1.0.

sdist: SDistSettings
search: SearchSettings
strict_config: bool = True

Strictly check all config options.

If False, warnings will be printed for unknown options.

If True, an error will be raised.

variant: List[str]

Experimental PEP 817 variant properties.

This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

Added in version 1.0.

variant_label: str | None = None

Experimental PEP 817 wheel variant label override.

This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

Added in version 1.0.

variant_name: List[str]

Experimental PEP 817 variant properties used for wheel metadata selection.

This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

Added in version 1.0.

wheel: WheelSettings
class scikit_build_core.settings.skbuild_model.SearchSettings(site_packages=True)[source]

Bases: object

site_packages: bool = True

Add the python build environment site_packages folder to the CMake prefix paths.

class scikit_build_core.settings.skbuild_model.SettingsFieldMetadata[source]

Bases: TypedDict

deprecated: bool
display_default: str | None
override_only: bool

Do not allow the field to be a top-level table.

class scikit_build_core.settings.skbuild_model.WheelSettings(packages=None, py_api='', expand_macos_universal_tags=False, install_dir='', license_files=None, cmake=True, platlib=None, exclude=<factory>, build_tag='', tags=None, force_include=<factory>, reproducible=False)[source]

Bases: object

build_tag: str = ''

The build tag to use for the wheel. If empty, no build tag is used.

cmake: bool = True

Run CMake as part of building the wheel.

exclude: List[str]

A set of patterns to exclude from the wheel.

This is additive to the SDist exclude patterns. This applies to the final paths in the wheel, and can exclude files from CMake output as well. Editable installs may not respect this exclusion.

expand_macos_universal_tags: bool = False

Fill out extra tags that are not required.

This adds “x86_64” and “arm64” to the list of platforms when “universal2” is used, which helps older Pip’s (before 21.0.1) find the correct wheel.

force_include: Dict[str, str]

Force-include files into the wheel.

Maps source paths to destinations relative to the platlib (the package area). Keys are relative to the project root; they may point outside it (e.g. ../shared) or be absolute, and ~ is expanded. A source may be a file or a directory; directories are copied recursively, skipping VCS and __pycache__ junk.

A ${SKBUILD_<TREE>_DIR} prefix (e.g. ${SKBUILD_DATA_DIR}/foo) targets that wheel tree instead of the platlib, matching the SKBUILD_*_DIR CMake cache variables (DATA, SCRIPTS, HEADERS, PLATLIB, METADATA, …). The deprecated leading-slash form (/data, /scripts, …) selects the same trees but requires experimental.

Force-included files are placed last, so they override discovered package files and CMake output at the same destination. A missing source is an error.

A force-included file also overrides wheel.exclude, since naming an exact source is an explicit request for that file. A force-included directory stays subject to wheel.exclude, so a bulk copy can still be trimmed by an exclude pattern.

If a source is missing on disk, it is looked up through sdist.force-include (by exact destination or under a force-included directory) and read from that original source instead. This lets a source that names an sdist output (vendored via sdist.force-include) build from both a source tree and an unpacked sdist.

In a redirect-mode editable install, platlib entries are served live from their sources through the import redirect instead of being copied: importable modules always, data files when they keep their filename and sit directly inside a top-level package. Anything else (other wheel trees; renamed, top-level, or nested data files) is still copied at install time.

Added in version 1.0.

install_dir: str = ''

The CMake install prefix relative to the platlib wheel path.

You might set this to the package name to install everything under the package namespace in a pythonic design.

The original dir is still at SKBUILD_PLATLIB_DIR (also SKBUILD_DATA_DIR, etc. are available).

A ${SKBUILD_<TREE>_DIR} prefix (e.g. ${SKBUILD_DATA_DIR}/foo) targets that wheel tree instead of the platlib, matching the SKBUILD_*_DIR CMake cache variables. Available trees: PLATLIB/PURELIB, DATA, HEADERS, SCRIPTS, METADATA, NULL.

Changed in version 1.0: Added the ${SKBUILD_<TREE>_DIR} prefix for targeting wheel trees.

Warning

EXPERIMENTAL A leading-slash absolute path (/platlib, /data, /headers, /scripts, …) is the deprecated spelling of the ${SKBUILD_<TREE>_DIR} form and is one level higher than the platlib root.

license_files: List[str] | None = None

A list of license files to include in the wheel. Supports glob patterns.

The default is ["LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*"].

Warning

Must not be set if project.license-files is set.

packages: List[str] | Dict[str, str] | None = None

A list of packages to auto-copy into the wheel.

If this is not set, it will default to the first of src/<package>, python/<package>, or <package> if they exist. The prefix(s) will be stripped from the package name inside the wheel.

An entry may also point at a single module file (e.g. hello.py), which is copied in as a top-level module rather than a package directory.

If a dict, provides a mapping of package name to source directory.

Changed in version 1.0: An entry may point at a single module file.

platlib: bool | None = None

Target the platlib or the purelib.

If not set, the default is to target the platlib if wheel.cmake is true, and the purelib otherwise.

py_api: str = ''

The Python version tag used in the wheel file.

The default (empty string) will use the default Python version.

You can also set this to “cp38” to enable the CPython 3.8+ Stable ABI / Limited API (only on CPython and if the version is sufficient, otherwise this has no effect). For free-threaded Python, you can use “cp315t” to enable the free-threaded stable ABI (only on CPython free-threaded builds and if the version is sufficient). You can request both with “cp315.cp315t”. On a free-threaded build this emits a combined “cp315-abi3.abi3t” tag: abi3t is a subset of abi3 (PEP 803), so the single free-threaded binary also loads under a GIL-enabled CPython 3.15+. On a GIL build only abi3 can be produced, so it falls back to “cp315-abi3”. The combined tag shares one minor version, so the classic abi3 minor must not be newer than the free-threaded one (e.g. “cp316.cp315t” is rejected). Or you can set it to “py3” or “py2.py3” to ignore Python ABI compatibility. The ABI tag is inferred from this tag.

This value is used to construct SKBUILD_SABI_COMPONENT CMake variable.

Changed in version 1.0: Added the free-threaded stable ABI (“cp315t”) and the combined abi3.abi3t tag (“cp315.cp315t”).

reproducible: bool = False

Try to build a reproducible wheel.

Unix and Python 3.9+ recommended.

When enabled, archive timestamps and file permissions are normalized, and SOURCE_DATE_EPOCH is exported to the CMake build (if not already set) so compilers that honor it can produce deterministic output. SOURCE_DATE_EPOCH is used for timestamps if set, or a fixed value if not.

Added in version 1.0.

tags: List[str] | None = None

Wheel tags to manually force, {interpreter}-{abi}-{platform} format.

Manually specify the wheel tags to use, ignoring other inputs such as wheel.py-api. Each tag must be of the format {interpreter}-{abi}-{platform}. If not specified, these tags are automatically calculated. This cannot be set in the static [tool.scikit-build] table; use it in an override, config-settings, or an environment variable.

scikit_build_core.settings.skbuild_overrides module

class scikit_build_core.settings.skbuild_overrides.OverrideRecord(key, original_value, value, passed_all, passed_any)[source]

Bases: object

Record of the override action.

Saves the original and final values, and the override reasons.

key: str

Settings key that is overridden.

original_value: Any | None

Original value in the pyproject table.

If the pyproject table did not have the key, this is a None.

passed_all: dict[str, str] | None

All if statements that passed (except the effective match_any).

passed_any: dict[str, str] | None

All if.any statements that passed.

value: Any

Final value.

scikit_build_core.settings.skbuild_overrides.process_overrides(tool_skb, *, state, retry, env=None)[source]

Process overrides into the main dictionary if they match. Modifies the input dictionary. Must be run from the package directory.

Return type:

tuple[set[str], dict[str, OverrideRecord]]

Returns:

A tuple of the set of matching overrides and a dict of changed keys and override record

scikit_build_core.settings.skbuild_overrides.regex_match(value, match)[source]

Returns a non-empty string if a value matches a regex.

Return type:

str

scikit_build_core.settings.skbuild_read_settings module

class scikit_build_core.settings.skbuild_read_settings.SettingsReader(pyproject, config_settings, *, state, extra_settings=None, verify_conf=True, env=None, retry=False)[source]

Bases: object

classmethod from_file(pyproject_path, config_settings=None, *, state='sdist', verify_conf=True, extra_settings=None, env=None, retry=False)[source]
Return type:

SettingsReader

print_suggestions()[source]
Return type:

None

suggestions(index)[source]
Return type:

dict[str, list[str]]

unrecognized_options()[source]
Return type:

Generator[str, None, None]

validate_may_exit()[source]
Return type:

None

scikit_build_core.settings.skbuild_schema module

scikit_build_core.settings.skbuild_schema.generate_skbuild_schema(tool_name='scikit-build')[source]

Generate the complete schema for scikit-build settings.

Return type:

dict[str, Any]

scikit_build_core.settings.skbuild_schema.get_skbuild_schema(tool_name='scikit-build')[source]

Get the stored complete schema for scikit-build settings.

Return type:

dict[str, Any]

scikit_build_core.settings.sources module

This module implements the configuration sources used by scikit-build-core. Each concrete Source adapts one input representation, such as environment variables, PEP 517 config-settings, or nested TOML tables, into the same nested dataclass model. SourceChain combines those sources and applies them in precedence order when building the final settings object.

An end user usually interacts with SourceChain, which takes a dataclass type and returns an instance with fields populated.

Example:

@dataclasses.dataclass
class ExampleSettings:
    generator: str = "Unix Makefiles"
    tags: list[str] = dataclasses.field(default_factory=list)
    defines: dict[str, str] = dataclasses.field(default_factory=dict)


pyproject = {
    "tool": {
        "example": {
            "generator": "Unix Makefiles",
            "defines": {"A": "1"},
        }
    }
}
env = {"EXAMPLE_TAGS": "fast;docs", "EXAMPLE_DEFINES": "B=2"}
config_settings = {"generator": "Ninja"}

sources = SourceChain(
    EnvSource("EXAMPLE", env=env),
    ConfSource(settings=config_settings),
    TOMLSource("tool", "example", settings=pyproject),
)
settings = sources.convert_target(ExampleSettings)

assert settings.generator == "Ninja"
assert settings.tags == ["fast", "docs"]
assert settings.defines == {"B": "2", "A": "1"}

unrecognized_options = list(sources.unrecognized_options(ExampleSettings))

Naming conventions:

  • model is the complete Dataclass.

  • target is the type to convert a single item to.

  • settings is the input data source (unless it already has a name, like env).

  • options are the names of the items in the model, formatted in the style of the current Source.

  • fields are the tuple of strings describing a nested field in the model.

Source representations:

  • EnvSource: reads values in environment variables. Lists are encoded as "a;b" and dicts as "key=value;other=value".

  • ConfSource: reads values in a flat mapping keyed by dotted option names from the command line, like -Ca.b=c.

  • TOMLSource: reads values in a nested TOML mapping, like in pyproject.toml.

  • SourceChain: queries sources in order and asks the first matching source to convert its native value into the requested dataclass field type.

When setting up your dataclasses, these types are handled:

  • str: A string type, nothing special.

  • bool: Supports bool in TOML, not handled in envvar/config (so only useful in a Union)

  • Any callable (Path, Version): Passed the string input.

  • Optional[T]: Treated like T. Default should be None, since no input format supports None’s.

  • Union[str, ...]: Supports other input types in TOML form (bool currently). Otherwise a string.

  • Union[str, List[str]]: A single string, or a list (a repeated option in config form, ; separated in EnvVar/config forms, or native in TOML).

  • List[T]: A list of items. ; separated supported in EnvVar/config forms. T can be a dataclass (TOML only).

  • Dict[str, T]: A table of items. TOML supports a layer of nesting. Any is supported as an item type.

  • Union[list[T], Dict[str, T]] (TOML only): A list or dict of items.

  • Literal[...]: A list of strings, the result must be in the list.

  • Annotated[Dict[...], "EnvVar"]: A dict of items, where each item can be a string or a dict with “env” and “default” keys.

These are supported for JSON schema generation for the TOML, as well.

Integers/floats would be easy to add, but haven’t been needed yet.

class scikit_build_core.settings.sources.ConfSource(*prefixes, settings, verify=True)[source]

Bases: Source

Source for PEP 517 config-settings.

While most mechanisms (pip, uv, build) only support text, gpep517 allows an arbitrary json input, so this currently also handles bools.

Example:

source = ConfSource(
    "skbuild",
    settings={
        "skbuild.logging.level": "DEBUG",
        "skbuild.cmake.define.CMAKE_CXX_STANDARD": "20",
    },
)

assert source.get_item("logging", "level", is_dict=False) == "DEBUG"
assert source.get_item("cmake", "define", is_dict=True) == {
    "CMAKE_CXX_STANDARD": "20"
}
all_option_names(target)[source]

Given a model, produce a list of all possible names (used for producing suggestions).

Return type:

Iterator[str]

classmethod convert(item, target)[source]

Convert a source-native item into the requested target type.

Raises TypeError if the conversion fails.

Return type:

object

get_item(*fields, is_dict)[source]

Return the source-native value for a field path.

The return type depends on the source: env returns a raw string, config-settings returns a string/list/bool or reconstructed dict, and TOML returns the native TOML object. Raises KeyError if the value is missing. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

str | list[str] | dict[str, str] | bool

has_item(*fields, is_dict)[source]

Check whether the source contains a field path.

For example, fields=("a", "b") asks whether the source has a value for the nested model field a.b. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

bool

prefixes: tuple[str, ...]

Dotted option-name segments prepended to every lookup.

settings: Mapping[str, str | list[str] | bool]

Flat backend config-settings mapping keyed by dotted option names.

Scalar values are stored directly. Dict-typed target fields are represented by multiple flat entries such as "sdist.include.foo" = "bar".

unrecognized_options(options)[source]

Given a model, produce an iterator of all unrecognized option names. Empty iterator if this can’t be computed for the source (like for environment variables).

Return type:

Generator[str, None, None]

verify: bool

Whether to report unrecognized dotted keys from this source.

Only disable this when the source intentionally shares a namespace with unrelated config keys.

class scikit_build_core.settings.sources.EnvSource(prefix, *, env=None)[source]

Bases: Source

Source backed by environment variables.

Nested field paths are represented by uppercased underscore-separated names such as PREFIX_A_B. Values remain raw strings in the environment until they are converted into the requested field type.

Example:

env = {
    "SKBUILD_CMAKE_ARGS": "-GNinja;-DCMAKE_BUILD_TYPE=Debug",
    "SKBUILD_CMAKE_DEFINE": "CMAKE_CXX_STANDARD=20;BUILD_TESTING=OFF",
}
source = EnvSource("SKBUILD", env=env)

assert source.get_item("cmake", "args", is_dict=False) == (
    "-GNinja;-DCMAKE_BUILD_TYPE=Debug"
)
assert source.get_item("cmake", "define", is_dict=False) == (
    "CMAKE_CXX_STANDARD=20;BUILD_TESTING=OFF"
)
all_option_names(target)[source]

Given a model, produce a list of all possible names (used for producing suggestions).

Return type:

Iterator[str]

classmethod convert(item, target)[source]

Convert an item from the environment (always a string) into a target type.

Return type:

object

get_item(*fields, is_dict)[source]

Return the source-native value for a field path.

The return type depends on the source: env returns a raw string, config-settings returns a string/list/bool or reconstructed dict, and TOML returns the native TOML object. Raises KeyError if the value is missing. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

str | dict[str, str]

has_item(*fields, is_dict)[source]

Check whether the source contains a field path.

For example, fields=("a", "b") asks whether the source has a value for the nested model field a.b. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

bool

static unrecognized_options(options)[source]

Given a model, produce an iterator of all unrecognized option names. Empty iterator if this can’t be computed for the source (like for environment variables).

Return type:

Generator[str, None, None]

class scikit_build_core.settings.sources.Source(*args, **kwargs)[source]

Bases: Protocol

all_option_names(target)[source]

Given a model, produce a list of all possible names (used for producing suggestions).

Return type:

Iterator[str]

classmethod convert(item, target)[source]

Convert a source-native item into the requested target type.

Raises TypeError if the conversion fails.

Return type:

object

get_item(*fields, is_dict)[source]

Return the source-native value for a field path.

The return type depends on the source: env returns a raw string, config-settings returns a string/list/bool or reconstructed dict, and TOML returns the native TOML object. Raises KeyError if the value is missing. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

Any

has_item(*fields, is_dict)[source]

Check whether the source contains a field path.

For example, fields=("a", "b") asks whether the source has a value for the nested model field a.b. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

bool

unrecognized_options(options)[source]

Given a model, produce an iterator of all unrecognized option names. Empty iterator if this can’t be computed for the source (like for environment variables).

Return type:

Generator[str, None, None]

class scikit_build_core.settings.sources.SourceChain(*sources, prefixes=())[source]

Bases: object

convert_target(target, *prefixes)[source]

Build a dataclass instance from the chained sources.

For each field, this first asks each source whether it has a native value for the current path. The first matching source returns that raw value via get_item, and that same source then normalizes it with convert into the dataclass field type. Nested dataclasses recurse into convert_target. Dict fields are special: later sources extend the dict assembled so far instead of replacing it outright.

Example:

@dataclasses.dataclass
class Example:
    tags: list[str] = dataclasses.field(default_factory=list)
    defines: dict[str, str] = dataclasses.field(default_factory=dict)


chain = SourceChain(
    EnvSource("EXAMPLE", env={"EXAMPLE_DEFINES": "A=1"}),
    ConfSource(settings={"tags": ["from-conf"]}),
    TOMLSource(settings={"tags": ["from-toml"], "defines": {"B": "2"}}),
)

settings = chain.convert_target(Example)

assert settings.tags == ["from-conf"]
assert settings.defines == {"A": "1", "B": "2"}
Return type:

TypeVar(T)

get_item(*fields, is_dict)[source]
Return type:

Any

has_item(*fields, is_dict)[source]
Return type:

bool

unrecognized_options(options)[source]
Return type:

Generator[str, None, None]

class scikit_build_core.settings.sources.TOMLSource(*prefixes, settings)[source]

Bases: Source

Source backed by a nested TOML mapping.

After applying any constructor prefixes, self.settings is the nested table for that subtree. get_item returns the native TOML value found at the requested field path, and convert turns that TOML value into the target dataclass field type.

Example:

source = TOMLSource(
    "tool",
    "scikit-build",
    settings={
        "tool": {
            "scikit-build": {
                "wheel": {"packages": ["src/example"]},
            }
        }
    },
)

assert source.get_item("wheel", "packages", is_dict=False) == ["src/example"]
all_option_names(target)[source]

Given a model, produce a list of all possible names (used for producing suggestions).

Return type:

Iterator[str]

classmethod convert(item, target)[source]

Convert an item from TOML into a target type.

Return type:

object

get_item(*fields, is_dict)[source]

Return the source-native value for a field path.

The return type depends on the source: env returns a raw string, config-settings returns a string/list/bool or reconstructed dict, and TOML returns the native TOML object. Raises KeyError if the value is missing. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

Any

has_item(*fields, is_dict)[source]

Check whether the source contains a field path.

For example, fields=("a", "b") asks whether the source has a value for the nested model field a.b. is_dict is set for dict-typed targets, because some sources represent dict entries as nested keys.

Return type:

bool

unrecognized_options(options)[source]

Given a model, produce an iterator of all unrecognized option names. Empty iterator if this can’t be computed for the source (like for environment variables).

Return type:

Generator[str, None, None]