Skip to content
Back to top

# API Documentation

build provides a Python API for programmatic use in build tools, CI systems, and automation scripts.

Note

When not using an isolated environment, the build backend must be installed in the current environment. When using `DefaultIsolatedEnv`, you must explicitly install build dependencies into the isolated environment via `install()` before calling `build()` — the environment is created empty.

## Basic Usage

Building a package programmatically:

    from build import ProjectBuilder

    builder = ProjectBuilder("path/to/project")
    builder.build("wheel", "dist/")

Building both sdist and wheel:

    from build import ProjectBuilder

    builder = ProjectBuilder(".")
    builder.build("sdist", "dist/")
    builder.build("wheel", "dist/")

Using isolated environments (default):

`DefaultIsolatedEnv` creates a clean virtual environment, but it is initially empty. You must install the project’s build dependencies before invoking the backend:

    from build import ProjectBuilder
    from build.env import DefaultIsolatedEnv

    with DefaultIsolatedEnv() as env:
        builder = ProjectBuilder.from_isolated_env(env, ".")
        # Install build-system.requires (e.g., flit-core, setuptools, ...)
        env.install(builder.build_system_requires)
        # Install additional backend dependencies for the target distribution
        env.install(builder.get_requires_for_build("wheel"))
        builder.build("wheel", "dist/")

Pass `path` to create the environment at a fixed location instead of a temporary directory. The location must be empty; `DefaultIsolatedEnv` removes it on a clean exit and keeps it when the block raises:

    with DefaultIsolatedEnv(path=".build-env") as env:
        builder = ProjectBuilder.from_isolated_env(env, ".")
        env.install(builder.build_system_requires)
        builder.build("wheel", "dist/")

Disabling isolation:

    from build import ProjectBuilder

    builder = ProjectBuilder(".", runner=lambda cmd, **kwargs: None)
    builder.build("wheel", "dist/")

Getting package metadata without building:

    from build import ProjectBuilder
    import tempfile

    builder = ProjectBuilder(".")
    with tempfile.TemporaryDirectory() as tmpdir:
        metadata_dir = builder.metadata_path(tmpdir)
        # Read METADATA file from metadata_dir to extract package info

Accessing build dependencies:

    from build import ProjectBuilder

    builder = ProjectBuilder(".")
    requires = builder.build_system_requires
    print(f"Build requires: {requires}")

    # Get additional dependencies for building a wheel
    wheel_requires = builder.get_requires_for_build("wheel")
    print(f"Wheel build requires: {wheel_requires}")

Handling errors:

    from build import ProjectBuilder
    from build import BuildException

    try:
        builder = ProjectBuilder(".")
        builder.build("wheel", "dist/")
    except BuildException as e:
        print(f"Build failed: {e}")

## Reference

## `build` module

build - A simple, correct Python build frontend

exception build.BuildBackendException(exception, description=None, exc_info=(None, None, None))

  Bases: `Exception`

  Exception raised when a backend operation fails.

exception build.BuildException

  Bases: `Exception`

  Exception raised by `build` when a build cannot proceed.

exception build.BuildSystemTableValidationError

  Bases: `BuildException`

  Exception raised when the `[build-system]` table in pyproject.toml is invalid.

exception build.FailedProcessError(exception, description)

  Bases: `Exception`

  Exception raised when a setup or preparation operation fails.

class build.ProjectBuilder(source_dir, python_executable='/usr/bin/python3.14', runner=<function default_subprocess_runner>)

  Bases: `object`

  The PEP 517 consumer API.

  Parameters:

    - source_dir (`str` | `PathLike`[`str`]) – The source directory

    - python_executable (`str`) – The python executable where the backend lives

    - runner (`Callable`[[`Sequence`[`str`], `str` | `None`, `Mapping`[`str`, `str`] | `None`], `None`]) – Runner for backend subprocesses

  The `runner`, if provided, must accept the following arguments:

  - `cmd`: a list of strings representing the command and arguments to execute, as would be passed to e.g. ‘subprocess.check_call’.

  - `cwd`: a string representing the working directory that must be used for the subprocess. Corresponds to the provided source_dir.

  - `extra_environ`: a dict mapping environment variable names to values which must be set for the subprocess execution.

  The default runner simply calls the backend hooks in a subprocess, writing backend output to stdout/stderr.

  build(distribution, output_directory, config_settings=None, metadata_directory=None)

    Build a distribution.

    Parameters:

      - distribution (`Literal`[`'sdist'`, `'wheel'`, `'editable'`]) – Distribution to build (`sdist` or `wheel`)

      - output_directory (`str` | `PathLike`[`str`]) – Directory to put the built distribution in

      - config_settings (`Mapping`[`str`, `str` | `Sequence`[`str`]] | `None`) – Config settings for the build backend

      - metadata_directory (`str` | `None`) – If provided, should be the return value of a previous `prepare` call on the same `distribution` kind

    Return type:

      `str`

    Returns:

      The full path to the built distribution

  property build_system_requires: set[str]

    The dependencies defined in the `pyproject.toml`’s `build-system.requires` field or the default build dependencies if `pyproject.toml` is missing or `build-system` is undefined.

  check_dependencies(distribution, config_settings=None)

    Return the dependencies which are not satisfied from the combined set of `build_system_requires` and `get_requires_for_build()` for a given distribution.

    Parameters:

      - distribution (`Literal`[`'sdist'`, `'wheel'`, `'editable'`]) – Distribution to check (`sdist` or `wheel`)

      - config_settings (`Mapping`[`str`, `str` | `Sequence`[`str`]] | `None`) – Config settings for the build backend

    Return type:

      `set`[`tuple`[`str`, `...`]]

    Returns:

      Set of variable-length unmet dependency tuples

  classmethod from_isolated_env(env, source_dir, runner=<function default_subprocess_runner>)
    Return type:

      `Self`

  get_requires_for_build(distribution, config_settings=None)

    Return the dependencies defined by the backend in addition to `build_system_requires` for a given distribution.

    Parameters:

      - distribution (`Literal`[`'sdist'`, `'wheel'`, `'editable'`]) – Distribution to get the dependencies of (`sdist` or `wheel`)

      - config_settings (`Mapping`[`str`, `str` | `Sequence`[`str`]] | `None`) – Config settings for the build backend

    Return type:

      `set`[`str`]

  metadata_path(output_directory)

    Generate the metadata directory of a distribution and return its path.

    If the backend does not support the `prepare_metadata_for_build_wheel` hook, a wheel will be built and the metadata will be extracted from it.

    Parameters:

      output_directory (`str` | `PathLike`[`str`]) – Directory to put the metadata distribution in

    Return type:

      `str`

    Returns:

      The path of the metadata directory

  prepare(distribution, output_directory, config_settings=None)

    Prepare metadata for a distribution.

    Parameters:

      - distribution (`Literal`[`'sdist'`, `'wheel'`, `'editable'`]) – Distribution to build (must be `wheel`)

      - output_directory (`str` | `PathLike`[`str`]) – Directory to put the prepared metadata in

      - config_settings (`Mapping`[`str`, `str` | `Sequence`[`str`]] | `None`) – Config settings for the build backend

    Return type:

      `str` | `None`

    Returns:

      The full path to the prepared metadata directory

  property python_executable: str

    The Python executable used to invoke the backend.

  property source_dir: str

    Project source directory.

exception build.TypoWarning

  Bases: `Warning`

  Warning raised when a possible typo is found.

build.check_dependency(req_string, ancestral_req_strings=(), parent_extras=frozenset({}))

  Verify that a dependency and all of its dependencies are met.

  Parameters:

    - req_string (`str`) – Requirement string

    - parent_extras (`Set`[`str`]) – Extras (eg. “test” in myproject[test])

  Yields:

    Unmet dependencies

## `build.env` module

class build.env.DefaultIsolatedEnv(*, installer='pip', path=None)

  Bases: `IsolatedEnv`

  Isolated environment which supports several different underlying implementations.

  install(requirements, constraints=(), *, _fresh=False)

    Install packages from PEP 508 requirements in the isolated build environment.

    Parameters:

      requirements (`Collection`[`str`]) – PEP 508 requirement specification to install

    Note:

      Passing non-PEP 508 strings will result in undefined behavior, you should not rely on it. It is merely an implementation detail, it may change any time without warning.

    Return type:

      `None`

  installed_versions(requirements)

    Map the canonical name of each requirement to the version installed in the environment.

    Requirements that resolved to nothing installed are omitted. Reads the distribution metadata directly from the environment’s `purelib` so no subprocess is spawned in the isolated environment.

    Parameters:

      requirements (`Collection`[`str`]) – PEP 508 requirement specifications to look up; non-PEP 508 entries (such as local paths or URLs accepted by `install()`) are skipped since their installed name cannot be derived

    Return type:

      `dict`[`str`, `str`]

  make_extra_environ()

    Generate additional env vars specific to the isolated environment.

    Return type:

      `dict`[`str`, `str`]

  property path: str

    The location of the isolated build environment.

  property python_executable: str

    The python executable of the isolated build environment.

class build.env.IsolatedEnv(*args, **kwargs)

  Bases: `Protocol`

  Isolated build environment ABC.

  abstractmethod make_extra_environ()

    Generate additional env vars specific to the isolated environment.

    Return type:

      `Mapping`[`str`, `str`] | `None`

  abstract property python_executable: str

    The Python executable of the isolated environment.

## `build.util` module

build.util.project_wheel_metadata(source_dir, isolated=True, *, runner=<function quiet_subprocess_runner>)

  Return the wheel metadata for a project.

  Uses the `prepare_metadata_for_build_wheel` hook if available, otherwise `build_wheel`.

  Deprecated since version 1.5.0: Generate metadata with the `python -m build --metadata` command instead.

  Parameters:

    - source_dir (`str` | `PathLike`[`str`]) – Project source directory

    - isolated (`bool`) – Whether or not to run invoke the backend in the current environment or to create an isolated one and invoke it there.

    - runner (`Callable`[[`Sequence`[`str`], `str` | `None`, `Mapping`[`str`, `str`] | `None`], `None`]) – An alternative runner for backend subprocesses

  Return type:

    `PackageMetadata`