Debian Codegraph @

docs/explanation/how-it-works.rst

raw
1 ##############
2 How it Works
3 ##############
4
5 This document explains how build works internally and the build process flow.
6
7 *******************
8 The Build Process
9 *******************
10
11 When you run ``python -m build``, the following happens:
12
13 .. mermaid::
14
15 %%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#4051b5','primaryTextColor':'#fff','primaryBorderColor':'#2c3e8f','lineColor':'#5468c4','secondaryColor':'#7c8fd6','tertiaryColor':'#e8eaf6'}}}%%
16 flowchart TD
17 A[Run python -m build] --> B[Read pyproject.toml]
18 B --> C{Isolated build?}
19 C -->|Yes default| D[Create temporary venv]
20 C -->|--no-isolation| E[Use current environment]
21 D --> F[Install build dependencies]
22 E --> F
23 F --> G[Invoke build backend hooks]
24 G --> H{Build what?}
25 H -->|Default| I[Build sdist]
26 I --> J[Extract sdist to temp dir]
27 J --> K[Build wheel from sdist]
28 H -->|--sdist| L[Build sdist only]
29 H -->|--wheel| M[Build wheel from source]
30 K --> N[Output to dist/]
31 L --> N
32 M --> N
33 N --> O[Cleanup temporary environment]
34 O --> P[Done]
35
36 style A fill:#4051b5,stroke:#2c3e8f,color:#fff
37 style P fill:#2e7d32,stroke:#1b5e20,color:#fff
38 style N fill:#f57c00,stroke:#e65100,color:#fff
39 style D fill:#7c8fd6,stroke:#5468c4,color:#fff
40 style G fill:#7c8fd6,stroke:#5468c4,color:#fff
41
42 The process in detail:
43
44 1. **Read pyproject.toml**
45
46 build reads your project's `pyproject.toml <https://packaging.python.org/en/latest/specifications/pyproject-toml/>`_
47 to determine:
48
49 - Which **build backend** to use (from ``[build-system]`` section)
50 - What dependencies the backend needs (``requires`` list)
51 - Build backend configuration (``backend-path`` if specified)
52
53 2. **Create isolated environment** (default behavior)
54
55 build creates a temporary `virtual environment <https://docs.python.org/3/tutorial/venv.html>`_ to ensure
56 reproducible builds:
57
58 - Creates a fresh virtualenv in a temporary directory
59 - Sets ``VIRTUAL_ENV`` `environment variable <https://docs.python.org/3/library/venv.html#how-venvs-work>`_
60 - Installs the build backend and its dependencies via `pip <https://pip.pypa.io/>`_
61
62 This isolation ensures your build doesn't depend on what's installed in your development environment, making builds
63 reproducible across different machines.
64
65 3. **Invoke build backend hooks**
66
67 build calls standardized hooks (functions) in your **build backend**:
68
69 - For source distributions: calls ``build_sdist(sdist_directory, config_settings=None)``
70 - For wheels: calls ``build_wheel(wheel_directory, config_settings=None, metadata_directory=None)``
71
72 These hooks are defined in :PEP:`517` (the build system interface standard).
73
74 build runs each hook in a subprocess and forwards its standard output and error straight through, so a failing
75 backend's messages reach your terminal regardless of verbosity (``-vv`` adds build's own diagnostics on top). build
76 cannot collect log *files* the backend writes inside its own working directory: :PEP:`517` exposes no way for a
77 frontend to learn where those live, so retrieving them depends on backend-specific settings. See
78 :ref:`debug-a-failed-build` for how to keep them.
79
80 4. **Build artifacts**
81
82 The backend creates `distribution files
83 <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_:
84
85 - **Source distribution (sdist)**: A `tarball
86 <https://packaging.python.org/en/latest/specifications/source-distribution-format/>`_ (``package-version.tar.gz``)
87 containing your source code
88 - **Wheel**: A `zip file <https://packaging.python.org/en/latest/specifications/binary-distribution-format/>`_
89 (``package-version-py3-none-any.whl``) that can be installed directly
90
91 5. **Cleanup**
92
93 build removes the temporary isolated environment, leaving only the distribution files in ``dist/``.
94
95 ************************
96 Default Build Strategy
97 ************************
98
99 By default, ``python -m build`` creates both sdist and wheel following this strategy:
100
101 1. Build sdist from source directory
102 2. Extract sdist to temporary directory
103 3. Build wheel from the extracted sdist
104
105 This "build wheel from sdist" strategy ensures your sdist is complete. If files are missing from the sdist, the wheel
106 build will fail, alerting you to the problem.
107
108 Step 2 defaults to a random temporary directory that build removes after the run. Build randomises the path on purpose:
109 it surfaces backends that hard-code absolute paths and keeps successive builds independent. That same randomness defeats
110 compiler caches keyed on the source path, so ``--sdist-extract-dir`` lets you opt into a stable, persistent location
111 when cache hits matter more than isolation.
112
113 If the positional argument is a ``.tar.gz`` rather than a directory, the default is **wheel-only**: build checks the
114 archive, extracts it into a temporary directory, and runs the wheel build against the extracted source. There is no
115 sdist step. The archive already is an sdist, and PEP 517 has no hook for turning one sdist into another, so ``--sdist``
116 against an sdist errors out.
117
118 ***************************
119 Build Isolation Explained
120 ***************************
121
122 Why isolation matters
123 =====================
124
125 Without isolation, builds can be non-reproducible. Different developers have different packages installed, and CI
126 environments may have different packages than local development. Upgrading a package in your dev environment could break
127 builds, and you might accidentally depend on a package that's not declared. Isolation solves this by creating a clean
128 environment for every build.
129
130 How isolation works
131 ===================
132
133 1. build creates a temporary virtual environment using Python's ``venv`` module
134 2. Installs only the packages listed in ``[build-system] requires``
135 3. Runs the build backend in this isolated environment
136 4. Deletes the environment after building
137
138 The isolated environment has access to the Python standard library, the build backend and its dependencies, and nothing
139 from your development environment except environment variables.
140
141 build picks a temporary directory for this environment by default and deletes it after the build. Pass ``--env-dir`` to
142 choose the location yourself. You might do this to keep a failed environment for inspection, to place the environment on
143 a writable path inside a read-only container, or to give a fixed path to a compilation cache such as ccache or sccache.
144 Those caches treat a changed build-environment path as a new file, so a path that changes every run never hits the
145 cache.
146
147 When to disable isolation
148 =========================
149
150 Use ``--no-isolation`` only when:
151
152 - You're in an offline/air-gapped environment and have pre-installed dependencies
153 - You're debugging build issues and need to inspect the environment
154 - You're a Linux distribution packager providing dependencies externally
155 - You understand the reproducibility implications
156
157 Under ``--no-isolation`` build installs nothing; it instead validates that the declared dependencies are already present
158 (use ``--skip-dependency-check`` to opt out), so a missing dependency is reported rather than silently producing a
159 broken build. That check compares each declared requirement against the installed metadata of the *single interpreter
160 running build*, discovered through ``importlib.metadata``. This explains two otherwise confusing outcomes, which the
161 error message spells out per requirement (``wanted`` versus ``found``). A package can be present but reported missing
162 because its installed version does not satisfy the specifier (``found`` shows that version). And a package you know is
163 installed can read as ``not installed`` when it was installed for a *different* Python — a system or distribution
164 package manager often targets an interpreter other than the one invoking build, and metadata is not shared across
165 interpreters. The error names the interpreter checked so the mismatch is visible rather than left to guesswork.
166
167 See :doc:`../how-to/basic-usage` for usage.
168
169 ***********************************
170 Build Frontends vs Build Backends
171 ***********************************
172
173 build is a **build frontend** that reads ``pyproject.toml``, creates isolated environments, invokes build backends, and
174 handles the command-line interface. It does NOT know how to build your specific package.
175
176 Your **build backend** (setuptools, hatchling, flit, etc.) knows how to build your package by implementing PEP 517
177 hooks. The backend handles package discovery, file inclusion, metadata generation, and creates the actual sdist and
178 wheel files.
179
180 This separation of concerns allows different backends for different project needs, ensures frontend improvements benefit
181 all backends, and allows backend improvements to work with all frontends.
182
183 See :doc:`build-backends` for more details.
184
185 *********************
186 PEP 517 Integration
187 *********************
188
189 build implements :PEP:`517` (the standardized build system interface that defines how build tools communicate with
190 backends). The key concepts:
191
192 Build system table
193 ==================
194
195 Your `pyproject.toml <https://packaging.python.org/en/latest/specifications/pyproject-toml/>`_ must have a
196 ``[build-system]`` section:
197
198 .. code-block:: toml
199
200 [build-system]
201 requires = ["hatchling"]
202 build-backend = "hatchling.build"
203
204 - ``requires``: Packages needed to build (installed in isolated environment)
205 - ``build-backend``: Python import path to backend object
206
207 Backend hooks
208 =============
209
210 build calls these standardized hooks in your backend:
211
212 - ``get_requires_for_build_sdist(config_settings)`` - Returns additional dependencies needed for sdist
213 - ``build_sdist(sdist_directory, config_settings)`` - Creates sdist, returns filename
214 - ``get_requires_for_build_wheel(config_settings)`` - Returns additional dependencies needed for wheel
215 - ``build_wheel(wheel_directory, config_settings, metadata_directory)`` - Creates wheel, returns filename
216
217 Optional hooks:
218
219 - ``prepare_metadata_for_build_wheel(metadata_directory, config_settings)`` - Generates wheel metadata without full
220 build
221
222 Config settings
223 ===============
224
225 The ``config_settings`` parameter in hooks receives settings from ``--config-setting`` / ``-C`` flags.
226
227 build converts:
228
229 .. code-block:: console
230
231 $ python -m build -C key=value
232
233 Into:
234
235 .. code-block:: python
236
237 config_settings = {"key": "value"}
238
239 The backend interprets these settings. See :doc:`../how-to/config-settings` for examples.
240
241 *********************
242 Metadata Extraction
243 *********************
244
245 build can extract package metadata without a full build:
246
247 .. code-block:: console
248
249 $ python -m build --metadata
250
251 This:
252
253 1. Creates isolated environment
254 2. Calls ``prepare_metadata_for_build_wheel()`` if available
255 3. Otherwise, calls ``build_wheel()`` and extracts metadata
256 4. Outputs metadata in JSON format to stdout
257
258 Useful for tools that need package metadata without building the full package.
259
260 ***************************
261 Diagnostics and Verbosity
262 ***************************
263
264 ``pyproject.toml`` declares build dependencies as *specifiers* (``setuptools >= 40.8.0``), not exact versions. The
265 installer resolves each specifier to a concrete version at build time, and on an isolated build that version lives only
266 in the temporary environment, which build deletes once it finishes. The installer's own output reports the versions, but
267 only at ``-vv``, interleaved with the rest of its log.
268
269 So once build has installed the dependencies it prints a concise summary of the resolved version of each, as
270 ``name==version``, the single piece a backend bug report usually asks for. build obtains these by reading the installed
271 distribution metadata from the environment's ``site-packages`` through ``importlib.metadata`` rather than by spawning a
272 process inside the environment, so the summary is cheap and works the same for the ``venv``/``virtualenv`` and ``uv``
273 backends. Because it reads installed metadata, it reflects what build used, including any transitive resolution the
274 specifier allowed.
275
276 This is an isolated-build concern. Under ``--no-isolation`` build installs nothing - it builds against the interpreter
277 that is already running it - so the versions are whatever that interpreter has, discoverable with your installer.
278
279 ****************
280 Error Handling
281 ****************
282
283 build performs minimal error handling:
284
285 - Validates ``pyproject.toml`` exists and is valid TOML
286 - Checks ``[build-system]`` section exists
287 - Verifies backend is importable
288 - Checks hook return values are valid
289
290 Most error handling is delegated to the backend. If the backend fails, build reports the error and exits.
291
292 This keeps build simple and focused on its role as a frontend.
293
294 *********************
295 Installer Selection
296 *********************
297
298 By default, build uses pip to install dependencies in isolated environments. You can use a different installer:
299
300 .. code-block:: console
301
302 $ python -m build --installer=uv
303
304 Requirements for custom installers:
305
306 - Must accept ``install`` command
307 - Must accept package specifications as arguments
308 - Must support ``--no-deps`` flag
309
310 Currently, pip and uv are the primary supported installers.
311
312 *****************************
313 Virtual Environment Backend
314 *****************************
315
316 build can use different virtual environment implementations:
317
318 - ``venv`` (default): Python's built-in venv module
319 - ``virtualenv``: Third-party virtualenv package
320
321 To use virtualenv:
322
323 .. code-block:: console
324
325 $ pip install build[virtualenv]
326 $ python -m build
327
328 virtualenv provides better SSL support on older Python versions, faster environment creation, and more features (though
329 build uses only basic functionality).
330
331 See :doc:`../how-to/corporate-environments` for when this matters.
332
333 ****************************
334 Output Directory Structure
335 ****************************
336
337 By default, build places files in ``dist/`` within your source directory:
338
339 .. code-block:: text
340
341 myproject/
342 ├── dist/
343 │ ├── myproject-1.0.0.tar.gz # sdist
344 │ └── myproject-1.0.0-py3-none-any.whl # wheel
345 ├── src/
346 │ └── myproject/
347 │ └── __init__.py
348 └── pyproject.toml
349
350 Use ``--outdir`` to change the output location:
351
352 .. code-block:: console
353
354 $ python -m build --outdir /tmp/build-output
355
356 *******************************
357 Environment Variable Handling
358 *******************************
359
360 build passes most environment variables to the build backend:
361
362 **Always passed**:
363
364 - ``PATH`` - For finding executables
365 - ``PYTHONPATH`` - For Python module discovery
366 - HTTP/HTTPS proxy variables
367 - SSL certificate variables
368 - Custom pip variables (``PIP_*``)
369
370 **Set by build**:
371
372 - ``VIRTUAL_ENV`` - Points to isolated environment (when using isolation)
373
374 **When using ``--no-isolation``**:
375
376 - All environment variables from your shell are passed through unchanged
377
378 This behavior allows corporate environments to configure pip via environment variables, build backends to use custom
379 environment variables, and proxy and SSL configuration to work transparently.
380
381 See :doc:`../reference/environment-variables` for details.
382
383 *********************
384 Reproducible Builds
385 *********************
386
387 build aims for reproducible builds by:
388
389 1. **Isolated environments**: Same dependencies every time
390 2. **Declared dependencies**: ``[build-system] requires`` is explicit
391 3. **Standardized interface**: PEP 517 hooks are well-defined
392 4. **Minimal intervention**: build doesn't modify your code or backend behavior
393
394 However, full reproducibility also requires pinned backend versions in ``requires``, reproducible builds in your backend
395 (some backends support ``SOURCE_DATE_EPOCH``), consistent Python version, and consistent platform for platform-specific
396 wheels.
397
398 ***************
399 Build Reports
400 ***************
401
402 The names of the distribution files build produces are not known ahead of time. They encode the version and, for wheels,
403 the Python, ABI and platform tags. Downstream steps such as uploading, signing, or recording checksums need a way to
404 learn what was built.
405
406 ``--report`` writes this information to a JSON file. It uses a file rather than ``stdout`` because the build backend
407 runs as a subprocess that inherits build's streams and may print to them, so a consumer could not separate the report
408 from backend chatter on ``stdout``. A file build controls keeps the machine-readable output apart from the human- and
409 backend-facing log. Build writes the report only after the build succeeds and replaces it atomically, so a consumer
410 never reads a half-written file. See :doc:`../reference/cli` for the schema.
411
412 ****************************
413 Performance Considerations
414 ****************************
415
416 Build time is dominated by:
417
418 1. **Environment creation**: Creating virtualenv (1-2 seconds)
419 2. **Dependency installation**: Installing backend and dependencies (varies)
420 3. **Backend build**: Actual package building (varies greatly)
421
422 Ways to speed up builds include using ``--installer=uv`` for faster dependency installation, using ``--no-isolation`` if
423 dependencies are pre-installed (loses reproducibility), installing ``build[virtualenv]`` for faster environment
424 creation, and using ``--wheel`` to skip sdist when not needed.
425
426 The default (isolation with pip) prioritizes reproducibility over speed.
427
428 **********
429 See also
430 **********
431
432 - :doc:`build-backends` for choosing and configuring backends
433 - `PEP 517 <https://peps.python.org/pep-0517/>`_ for the build system specification
434 - `PEP 518 <https://peps.python.org/pep-0518/>`_ for the ``pyproject.toml`` specification