0
# PEP 517 Build Backend API
1
2
The `poetry.core.masonry.api` module provides a complete PEP 517 compliant build backend implementation. This allows Poetry-managed projects to be built by any PEP 517-compatible build frontend like `pip`, `build`, or other packaging tools.
3
4
## Core Import
5
6
```python
7
import poetry.core.masonry.api as build_api
8
``` { .api }
9
10
## Build Requirements Functions
11
12
### get_requires_for_build_wheel
13
14
```python
15
def get_requires_for_build_wheel(
16
config_settings: dict[str, Any] | None = None,
17
) -> list[str]:
18
"""
19
Returns additional requirements for building wheels.
20
21
Args:
22
config_settings: Optional build configuration settings from frontend
23
24
Returns:
25
List of PEP 508 requirement strings needed for wheel building.
26
Currently returns empty list as Poetry Core is self-contained.
27
28
Note:
29
This implementation is optional per PEP 517. Currently returns
30
empty list which is equivalent to not defining the function.
31
"""
32
``` { .api }
33
34
### get_requires_for_build_sdist
35
36
```python
37
def get_requires_for_build_sdist(
38
config_settings: dict[str, Any] | None = None,
39
) -> list[str]:
40
"""
41
Returns additional requirements for building source distributions.
42
43
Args:
44
config_settings: Optional build configuration settings from frontend
45
46
Returns:
47
List of PEP 508 requirement strings needed for sdist building.
48
Currently identical to wheel requirements (empty list).
49
"""
50
``` { .api }
51
52
### get_requires_for_build_editable
53
54
```python
55
get_requires_for_build_editable = get_requires_for_build_wheel
56
``` { .api }
57
58
Alias for `get_requires_for_build_wheel` - editable installs have same requirements as regular wheel builds.
59
60
## Metadata Preparation
61
62
### prepare_metadata_for_build_wheel
63
64
```python
65
def prepare_metadata_for_build_wheel(
66
metadata_directory: str,
67
config_settings: dict[str, Any] | None = None
68
) -> str:
69
"""
70
Prepares wheel metadata without building the full wheel.
71
72
Args:
73
metadata_directory: Directory path where metadata should be written
74
config_settings: Optional build configuration from frontend
75
76
Returns:
77
Name of the prepared metadata directory (typically ending in .dist-info)
78
79
Raises:
80
PyProjectError: If pyproject.toml is invalid or missing
81
ValidationError: If project configuration is invalid
82
83
Note:
84
Creates .dist-info directory with METADATA, WHEEL, and other files
85
needed for installation planning without full package building.
86
"""
87
``` { .api }
88
89
### prepare_metadata_for_build_editable
90
91
```python
92
prepare_metadata_for_build_editable = prepare_metadata_for_build_wheel
93
``` { .api }
94
95
Alias for `prepare_metadata_for_build_wheel` - editable installs use same metadata preparation.
96
97
## Package Building Functions
98
99
### build_wheel
100
101
```python
102
def build_wheel(
103
wheel_directory: str,
104
config_settings: dict[str, Any] | None = None,
105
metadata_directory: str | None = None,
106
) -> str:
107
"""
108
Builds a wheel package.
109
110
Args:
111
wheel_directory: Directory where the wheel should be written
112
config_settings: Optional build configuration from frontend
113
metadata_directory: Optional directory containing prepared metadata
114
115
Returns:
116
Filename of the built wheel (e.g., "package-1.0.0-py3-none-any.whl")
117
118
Raises:
119
PyProjectError: If pyproject.toml is invalid or missing
120
ValidationError: If project configuration is invalid
121
BuildError: If wheel building fails
122
123
Example:
124
>>> filename = build_wheel("./dist")
125
>>> print(f"Built wheel: {filename}")
126
Built wheel: my_package-1.0.0-py3-none-any.whl
127
"""
128
``` { .api }
129
130
### build_sdist
131
132
```python
133
def build_sdist(
134
sdist_directory: str,
135
config_settings: dict[str, Any] | None = None
136
) -> str:
137
"""
138
Builds a source distribution package.
139
140
Args:
141
sdist_directory: Directory where the sdist should be written
142
config_settings: Optional build configuration from frontend
143
144
Returns:
145
Filename of the built sdist (e.g., "package-1.0.0.tar.gz")
146
147
Raises:
148
PyProjectError: If pyproject.toml is invalid or missing
149
ValidationError: If project configuration is invalid
150
BuildError: If sdist building fails
151
152
Example:
153
>>> filename = build_sdist("./dist")
154
>>> print(f"Built sdist: {filename}")
155
Built sdist: my_package-1.0.0.tar.gz
156
"""
157
``` { .api }
158
159
### build_editable
160
161
```python
162
def build_editable(
163
wheel_directory: str,
164
config_settings: dict[str, Any] | None = None,
165
metadata_directory: str | None = None,
166
) -> str:
167
"""
168
Builds an editable wheel package for development installs.
169
170
Args:
171
wheel_directory: Directory where the editable wheel should be written
172
config_settings: Optional build configuration from frontend
173
metadata_directory: Optional directory containing prepared metadata
174
175
Returns:
176
Filename of the built editable wheel
177
178
Raises:
179
PyProjectError: If pyproject.toml is invalid or missing
180
ValidationError: If project configuration is invalid
181
BuildError: If editable wheel building fails
182
183
Note:
184
Editable wheels allow in-place development where changes to source
185
code are immediately reflected without reinstalling the package.
186
"""
187
``` { .api }
188
189
## Configuration Settings
190
191
The `config_settings` parameter in all functions accepts build configuration from the frontend. Poetry Core supports these common settings:
192
193
### Supported Config Settings
194
195
```python
196
# Example config_settings usage
197
config_settings = {
198
# Build options passed to underlying builders
199
"--build-option": ["--plat-name", "linux_x86_64"],
200
201
# Global build options
202
"--global-option": ["--verbose"],
203
204
# Environment variables for build process
205
"env": {"POETRY_CORE_DEBUG": "1"}
206
}
207
``` { .api }
208
209
## Complete Usage Examples
210
211
### Basic PEP 517 Build Script
212
213
```python
214
#!/usr/bin/env python3
215
"""Example build script using Poetry Core backend directly."""
216
217
import tempfile
218
from pathlib import Path
219
import poetry.core.masonry.api as build_api
220
221
def build_project(source_dir: Path, output_dir: Path):
222
"""Build both wheel and sdist for a Poetry project."""
223
224
# Change to source directory
225
original_cwd = Path.cwd()
226
try:
227
import os
228
os.chdir(source_dir)
229
230
# Build wheel
231
wheel_name = build_api.build_wheel(str(output_dir))
232
print(f"Built wheel: {wheel_name}")
233
234
# Build source distribution
235
sdist_name = build_api.build_sdist(str(output_dir))
236
print(f"Built sdist: {sdist_name}")
237
238
return wheel_name, sdist_name
239
240
finally:
241
os.chdir(original_cwd)
242
243
# Usage
244
if __name__ == "__main__":
245
source = Path("./my-poetry-project")
246
dist = Path("./dist")
247
dist.mkdir(exist_ok=True)
248
249
wheel, sdist = build_project(source, dist)
250
``` { .api }
251
252
### Integration with Build Tools
253
254
```python
255
# pyproject.toml configuration for using Poetry Core backend
256
"""
257
[build-system]
258
requires = ["poetry-core"]
259
build-backend = "poetry.core.masonry.api"
260
"""
261
262
# Example using 'build' package
263
from pathlib import Path
264
import build
265
266
def build_with_frontend(project_path: Path, output_dir: Path):
267
"""Build using the 'build' package as frontend."""
268
269
builder = build.ProjectBuilder(project_path)
270
271
# Build wheel
272
wheel_path = builder.build("wheel", output_dir)
273
print(f"Wheel built: {wheel_path}")
274
275
# Build sdist
276
sdist_path = builder.build("sdist", output_dir)
277
print(f"Sdist built: {sdist_path}")
278
279
return wheel_path, sdist_path
280
``` { .api }
281
282
### Metadata Inspection
283
284
```python
285
import tempfile
286
from pathlib import Path
287
import poetry.core.masonry.api as build_api
288
289
def inspect_metadata(project_dir: Path):
290
"""Extract and inspect package metadata without full build."""
291
292
original_cwd = Path.cwd()
293
try:
294
import os
295
os.chdir(project_dir)
296
297
with tempfile.TemporaryDirectory() as temp_dir:
298
# Prepare metadata
299
metadata_name = build_api.prepare_metadata_for_build_wheel(temp_dir)
300
metadata_dir = Path(temp_dir) / metadata_name
301
302
# Read METADATA file
303
metadata_file = metadata_dir / "METADATA"
304
if metadata_file.exists():
305
print("Package Metadata:")
306
print(metadata_file.read_text())
307
308
# List all metadata files
309
print(f"\nMetadata files in {metadata_name}:")
310
for file in metadata_dir.iterdir():
311
print(f" {file.name}")
312
313
finally:
314
os.chdir(original_cwd)
315
``` { .api }
316
317
## Error Handling
318
319
### Common Exceptions
320
321
```python
322
from poetry.core.exceptions import (
323
PoetryCoreError,
324
PyProjectError,
325
ValidationError
326
)
327
328
def safe_build_wheel(wheel_dir: str):
329
"""Build wheel with comprehensive error handling."""
330
331
try:
332
return build_api.build_wheel(wheel_dir)
333
334
except PyProjectError as e:
335
print(f"PyProject configuration error: {e}")
336
# Handle invalid pyproject.toml
337
338
except ValidationError as e:
339
print(f"Project validation error: {e}")
340
# Handle schema validation failures
341
342
except PoetryCoreError as e:
343
print(f"Poetry Core error: {e}")
344
# Handle other Poetry-specific errors
345
346
except Exception as e:
347
print(f"Unexpected build error: {e}")
348
# Handle system/IO errors
349
350
return None
351
``` { .api }
352
353
## Build Backend Integration
354
355
### Frontend Compatibility
356
357
Poetry Core's build backend is compatible with:
358
359
- **pip** - `pip install .` or `pip wheel .`
360
- **build** - `python -m build`
361
- **PyPA/build** - Programmatic building
362
- **tox** - Automated testing with different environments
363
- **cibuildwheel** - Cross-platform wheel building
364
- **setuptools-scm** - Version from VCS tags (with configuration)
365
366
### Performance Considerations
367
368
```python
369
# For better performance in CI/CD:
370
config_settings = {
371
# Skip tests during wheel building
372
"--skip-tests": "true",
373
374
# Use faster compression
375
"--wheel-compression": "deflate",
376
377
# Parallel processing when supported
378
"--parallel": "auto"
379
}
380
381
# Note: Actual support depends on Poetry Core version
382
wheel = build_api.build_wheel("./dist", config_settings=config_settings)
383
``` { .api }
384
385
## Type Definitions
386
387
```python
388
from typing import Any
389
390
# Configuration settings type
391
ConfigSettings = dict[str, Any] | None
392
393
# Return types
394
RequirementsList = list[str]
395
FileName = str
396
MetadataDirectoryName = str
397
``` { .api }
398
399
## Debugging and Logging
400
401
```python
402
import logging
403
404
# Enable Poetry Core debug logging
405
logging.basicConfig(level=logging.DEBUG)
406
logger = logging.getLogger("poetry.core")
407
408
# The build backend will log detailed information about:
409
# - Project discovery and validation
410
# - Dependency resolution
411
# - File collection and processing
412
# - Build artifact creation
413
``` { .api }