0
# Build System
1
2
PEP 517/518 compliant build backend for creating wheel and source distributions. Integrates with Python packaging standards for distribution creation and publishing workflows.
3
4
## Capabilities
5
6
### Build Backend API
7
8
Poetry's PEP 517/518 compliant build backend for creating Python distributions.
9
10
```python { .api }
11
def build_wheel(wheel_directory: str, config_settings: dict = None,
12
metadata_directory: str = None) -> str:
13
"""
14
Build wheel distribution.
15
16
Args:
17
wheel_directory: Directory to place the wheel
18
config_settings: Build configuration settings
19
metadata_directory: Directory containing prepared metadata
20
21
Returns:
22
Filename of the built wheel
23
24
Raises:
25
BuildError: If wheel building fails
26
"""
27
28
def build_sdist(sdist_directory: str, config_settings: dict = None) -> str:
29
"""
30
Build source distribution.
31
32
Args:
33
sdist_directory: Directory to place the source distribution
34
config_settings: Build configuration settings
35
36
Returns:
37
Filename of the built source distribution
38
39
Raises:
40
BuildError: If source distribution building fails
41
"""
42
43
def get_requires_for_build_wheel(config_settings: dict = None) -> list:
44
"""
45
Get build requirements for wheel building.
46
47
Args:
48
config_settings: Build configuration settings
49
50
Returns:
51
List of build requirement specifications
52
"""
53
54
def get_requires_for_build_sdist(config_settings: dict = None) -> list:
55
"""
56
Get build requirements for source distribution building.
57
58
Args:
59
config_settings: Build configuration settings
60
61
Returns:
62
List of build requirement specifications
63
"""
64
65
def prepare_metadata_for_build_wheel(metadata_directory: str,
66
config_settings: dict = None) -> str:
67
"""
68
Prepare wheel metadata without building the wheel.
69
70
Args:
71
metadata_directory: Directory to place metadata
72
config_settings: Build configuration settings
73
74
Returns:
75
Name of the prepared metadata directory
76
"""
77
```
78
79
#### Usage Example
80
81
```python
82
from poetry.masonry import api
83
84
# Build wheel distribution
85
wheel_filename = api.build_wheel("dist/")
86
print(f"Built wheel: {wheel_filename}")
87
88
# Build source distribution
89
sdist_filename = api.build_sdist("dist/")
90
print(f"Built source distribution: {sdist_filename}")
91
92
# Get build requirements
93
wheel_reqs = api.get_requires_for_build_wheel()
94
sdist_reqs = api.get_requires_for_build_sdist()
95
96
print(f"Wheel build requirements: {wheel_reqs}")
97
print(f"Source build requirements: {sdist_reqs}")
98
99
# Prepare metadata only
100
metadata_dir = api.prepare_metadata_for_build_wheel("build/")
101
print(f"Prepared metadata in: {metadata_dir}")
102
```
103
104
### Build Configuration
105
106
Configuration options for customizing the build process.
107
108
```python { .api }
109
class BuildConfig:
110
"""
111
Build configuration and options.
112
113
Manages build settings, file inclusion/exclusion,
114
and build-time customizations.
115
"""
116
117
def __init__(self, config_settings: dict = None):
118
"""
119
Initialize build configuration.
120
121
Args:
122
config_settings: Build configuration settings
123
"""
124
125
@property
126
def include_patterns(self) -> list:
127
"""File patterns to include in distribution."""
128
129
@property
130
def exclude_patterns(self) -> list:
131
"""File patterns to exclude from distribution."""
132
133
@property
134
def build_directory(self) -> Path:
135
"""Build output directory."""
136
137
def should_include(self, file_path: Path) -> bool:
138
"""
139
Check if file should be included in distribution.
140
141
Args:
142
file_path: Path to check
143
144
Returns:
145
True if file should be included
146
"""
147
148
def get_build_requirements(self) -> list:
149
"""
150
Get build requirements for current configuration.
151
152
Returns:
153
List of build requirement specifications
154
"""
155
```
156
157
### Package Building
158
159
High-level package building utilities and orchestration.
160
161
```python { .api }
162
class PackageBuilder:
163
"""
164
High-level package building orchestration.
165
166
Handles building packages with dependency resolution,
167
file collection, and distribution creation.
168
"""
169
170
def __init__(self, poetry: Poetry, env: Env, io = None):
171
"""
172
Initialize package builder.
173
174
Args:
175
poetry: Poetry instance
176
env: Build environment
177
io: IO interface
178
"""
179
180
def build(self, format_: str = "wheel", target_dir: Path = None) -> Path:
181
"""
182
Build package in specified format.
183
184
Args:
185
format_: Distribution format ("wheel" or "sdist")
186
target_dir: Target directory for built package
187
188
Returns:
189
Path to built package
190
"""
191
192
def build_all(self, target_dir: Path = None) -> list[Path]:
193
"""
194
Build all distribution formats.
195
196
Args:
197
target_dir: Target directory for built packages
198
199
Returns:
200
List of paths to built packages
201
"""
202
203
def get_metadata(self) -> dict:
204
"""
205
Get package metadata for distribution.
206
207
Returns:
208
Package metadata dictionary
209
"""
210
211
def collect_files(self) -> list[Path]:
212
"""
213
Collect files to include in distribution.
214
215
Returns:
216
List of file paths to include
217
"""
218
```
219
220
#### Usage Example
221
222
```python
223
from poetry.masonry.builders.package_builder import PackageBuilder
224
from poetry.factory import Factory
225
from poetry.utils.env import EnvManager
226
227
# Create Poetry instance and environment
228
poetry = Factory().create_poetry()
229
env_manager = EnvManager(poetry.file.parent)
230
env = env_manager.create_venv()
231
232
# Create package builder
233
builder = PackageBuilder(poetry, env)
234
235
# Build wheel
236
wheel_path = builder.build("wheel", target_dir=Path("dist"))
237
print(f"Built wheel: {wheel_path}")
238
239
# Build source distribution
240
sdist_path = builder.build("sdist", target_dir=Path("dist"))
241
print(f"Built source distribution: {sdist_path}")
242
243
# Build all formats
244
all_builds = builder.build_all(target_dir=Path("dist"))
245
for build_path in all_builds:
246
print(f"Built: {build_path}")
247
```
248
249
### Wheel Building
250
251
Specific utilities for wheel distribution creation.
252
253
```python { .api }
254
class WheelBuilder:
255
"""
256
Wheel distribution builder.
257
258
Handles creation of wheel (.whl) distributions with
259
proper metadata, file organization, and compression.
260
"""
261
262
def __init__(self, poetry: Poetry):
263
"""
264
Initialize wheel builder.
265
266
Args:
267
poetry: Poetry instance
268
"""
269
270
def build(self, target_dir: Path) -> Path:
271
"""
272
Build wheel distribution.
273
274
Args:
275
target_dir: Target directory
276
277
Returns:
278
Path to built wheel file
279
"""
280
281
def get_wheel_filename(self) -> str:
282
"""
283
Get wheel filename based on package metadata.
284
285
Returns:
286
Wheel filename
287
"""
288
289
def write_metadata(self, wheel_dir: Path) -> None:
290
"""
291
Write wheel metadata files.
292
293
Args:
294
wheel_dir: Wheel build directory
295
"""
296
```
297
298
### Source Distribution Building
299
300
Utilities for source distribution creation.
301
302
```python { .api }
303
class SdistBuilder:
304
"""
305
Source distribution builder.
306
307
Handles creation of source distributions (.tar.gz) with
308
proper file inclusion and packaging.
309
"""
310
311
def __init__(self, poetry: Poetry):
312
"""
313
Initialize source distribution builder.
314
315
Args:
316
poetry: Poetry instance
317
"""
318
319
def build(self, target_dir: Path) -> Path:
320
"""
321
Build source distribution.
322
323
Args:
324
target_dir: Target directory
325
326
Returns:
327
Path to built source distribution
328
"""
329
330
def get_sdist_filename(self) -> str:
331
"""
332
Get source distribution filename.
333
334
Returns:
335
Source distribution filename
336
"""
337
338
def collect_source_files(self) -> list[Path]:
339
"""
340
Collect source files for distribution.
341
342
Returns:
343
List of source file paths
344
"""
345
```
346
347
### Build Environment
348
349
Specialized build environment management for package building.
350
351
```python { .api }
352
def create_build_environment(poetry: Poetry, env: Env, io = None) -> Env:
353
"""
354
Create isolated build environment.
355
356
Args:
357
poetry: Poetry instance
358
env: Base environment
359
io: IO interface
360
361
Returns:
362
Build environment with dependencies installed
363
"""
364
365
def install_build_dependencies(env: Env, requirements: list) -> None:
366
"""
367
Install build dependencies in environment.
368
369
Args:
370
env: Build environment
371
requirements: List of build requirements
372
373
Raises:
374
BuildError: If dependency installation fails
375
"""
376
377
def validate_build_environment(env: Env, requirements: list) -> bool:
378
"""
379
Validate build environment has required dependencies.
380
381
Args:
382
env: Environment to validate
383
requirements: Required build dependencies
384
385
Returns:
386
True if environment is valid for building
387
"""
388
```
389
390
## Advanced Build Patterns
391
392
### Custom Build Scripts
393
394
```python
395
from poetry.masonry.api import build_wheel, build_sdist
396
397
def custom_build_process():
398
"""Custom build process with pre/post build steps."""
399
400
# Pre-build steps
401
print("Running pre-build steps...")
402
run_code_generation()
403
compile_assets()
404
405
# Build distributions
406
wheel_file = build_wheel("dist/")
407
sdist_file = build_sdist("dist/")
408
409
# Post-build steps
410
print("Running post-build steps...")
411
sign_distributions([wheel_file, sdist_file])
412
upload_to_registry([wheel_file, sdist_file])
413
414
return wheel_file, sdist_file
415
416
def run_code_generation():
417
"""Generate code before building."""
418
pass
419
420
def compile_assets():
421
"""Compile static assets."""
422
pass
423
424
def sign_distributions(files):
425
"""Sign distribution files."""
426
pass
427
428
def upload_to_registry(files):
429
"""Upload to package registry."""
430
pass
431
```
432
433
### Build Configuration in pyproject.toml
434
435
```toml
436
[tool.poetry.build]
437
# Include additional files
438
include = [
439
"README.md",
440
"LICENSE",
441
"data/*.json"
442
]
443
444
# Exclude files from distribution
445
exclude = [
446
"tests/",
447
"docs/",
448
"*.log"
449
]
450
451
# Build script configuration
452
script = "build_script.py"
453
```
454
455
### Programmatic Building
456
457
```python
458
from poetry.factory import Factory
459
from poetry.masonry.builders.package_builder import PackageBuilder
460
from poetry.utils.env import build_environment
461
462
def build_project_programmatically(project_path):
463
"""Build project programmatically."""
464
# Create Poetry instance
465
poetry = Factory().create_poetry(cwd=project_path)
466
467
# Create build environment
468
env_manager = EnvManager(poetry.file.parent)
469
base_env = env_manager.create_venv()
470
build_env = build_environment(poetry, base_env)
471
472
# Create builder
473
builder = PackageBuilder(poetry, build_env)
474
475
# Build all formats
476
distributions = builder.build_all(target_dir=project_path / "dist")
477
478
return distributions
479
```
480
481
## Error Handling
482
483
Build system exceptions and error conditions:
484
485
```python { .api }
486
class BuildError(PoetryError):
487
"""Base build system error."""
488
489
class BuildBackendError(BuildError):
490
"""Build backend operation failures."""
491
492
class BuildRequirementError(BuildError):
493
"""Build requirement installation or resolution errors."""
494
495
class PackagingError(BuildError):
496
"""Package creation and formatting errors."""
497
498
class MetadataError(BuildError):
499
"""Package metadata generation errors."""
500
```
501
502
Common build errors:
503
- Missing or invalid build dependencies
504
- File permission errors during building
505
- Invalid package metadata or configuration
506
- Build script execution failures
507
- Insufficient disk space for build artifacts
508
- Compression or archival errors during packaging