Poetry PEP 517 Build Backend for building Python packages with lightweight, compliant, self-contained build system
—
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.
import poetry.core.masonry.api as build_api
``` { .api }
## Build Requirements Functions
### get_requires_for_build_wheel
```python
def get_requires_for_build_wheel(
config_settings: dict[str, Any] | None = None,
) -> list[str]:
"""
Returns additional requirements for building wheels.
Args:
config_settings: Optional build configuration settings from frontend
Returns:
List of PEP 508 requirement strings needed for wheel building.
Currently returns empty list as Poetry Core is self-contained.
Note:
This implementation is optional per PEP 517. Currently returns
empty list which is equivalent to not defining the function.
"""
``` { .api }
### get_requires_for_build_sdist
```python
def get_requires_for_build_sdist(
config_settings: dict[str, Any] | None = None,
) -> list[str]:
"""
Returns additional requirements for building source distributions.
Args:
config_settings: Optional build configuration settings from frontend
Returns:
List of PEP 508 requirement strings needed for sdist building.
Currently identical to wheel requirements (empty list).
"""
``` { .api }
### get_requires_for_build_editable
```python
get_requires_for_build_editable = get_requires_for_build_wheel
``` { .api }
Alias for `get_requires_for_build_wheel` - editable installs have same requirements as regular wheel builds.
## Metadata Preparation
### prepare_metadata_for_build_wheel
```python
def prepare_metadata_for_build_wheel(
metadata_directory: str,
config_settings: dict[str, Any] | None = None
) -> str:
"""
Prepares wheel metadata without building the full wheel.
Args:
metadata_directory: Directory path where metadata should be written
config_settings: Optional build configuration from frontend
Returns:
Name of the prepared metadata directory (typically ending in .dist-info)
Raises:
PyProjectError: If pyproject.toml is invalid or missing
ValidationError: If project configuration is invalid
Note:
Creates .dist-info directory with METADATA, WHEEL, and other files
needed for installation planning without full package building.
"""
``` { .api }
### prepare_metadata_for_build_editable
```python
prepare_metadata_for_build_editable = prepare_metadata_for_build_wheel
``` { .api }
Alias for `prepare_metadata_for_build_wheel` - editable installs use same metadata preparation.
## Package Building Functions
### build_wheel
```python
def build_wheel(
wheel_directory: str,
config_settings: dict[str, Any] | None = None,
metadata_directory: str | None = None,
) -> str:
"""
Builds a wheel package.
Args:
wheel_directory: Directory where the wheel should be written
config_settings: Optional build configuration from frontend
metadata_directory: Optional directory containing prepared metadata
Returns:
Filename of the built wheel (e.g., "package-1.0.0-py3-none-any.whl")
Raises:
PyProjectError: If pyproject.toml is invalid or missing
ValidationError: If project configuration is invalid
BuildError: If wheel building fails
Example:
>>> filename = build_wheel("./dist")
>>> print(f"Built wheel: {filename}")
Built wheel: my_package-1.0.0-py3-none-any.whl
"""
``` { .api }
### build_sdist
```python
def build_sdist(
sdist_directory: str,
config_settings: dict[str, Any] | None = None
) -> str:
"""
Builds a source distribution package.
Args:
sdist_directory: Directory where the sdist should be written
config_settings: Optional build configuration from frontend
Returns:
Filename of the built sdist (e.g., "package-1.0.0.tar.gz")
Raises:
PyProjectError: If pyproject.toml is invalid or missing
ValidationError: If project configuration is invalid
BuildError: If sdist building fails
Example:
>>> filename = build_sdist("./dist")
>>> print(f"Built sdist: {filename}")
Built sdist: my_package-1.0.0.tar.gz
"""
``` { .api }
### build_editable
```python
def build_editable(
wheel_directory: str,
config_settings: dict[str, Any] | None = None,
metadata_directory: str | None = None,
) -> str:
"""
Builds an editable wheel package for development installs.
Args:
wheel_directory: Directory where the editable wheel should be written
config_settings: Optional build configuration from frontend
metadata_directory: Optional directory containing prepared metadata
Returns:
Filename of the built editable wheel
Raises:
PyProjectError: If pyproject.toml is invalid or missing
ValidationError: If project configuration is invalid
BuildError: If editable wheel building fails
Note:
Editable wheels allow in-place development where changes to source
code are immediately reflected without reinstalling the package.
"""
``` { .api }
## Configuration Settings
The `config_settings` parameter in all functions accepts build configuration from the frontend. Poetry Core supports these common settings:
### Supported Config Settings
```python
# Example config_settings usage
config_settings = {
# Build options passed to underlying builders
"--build-option": ["--plat-name", "linux_x86_64"],
# Global build options
"--global-option": ["--verbose"],
# Environment variables for build process
"env": {"POETRY_CORE_DEBUG": "1"}
}
``` { .api }
## Complete Usage Examples
### Basic PEP 517 Build Script
```python
#!/usr/bin/env python3
"""Example build script using Poetry Core backend directly."""
import tempfile
from pathlib import Path
import poetry.core.masonry.api as build_api
def build_project(source_dir: Path, output_dir: Path):
"""Build both wheel and sdist for a Poetry project."""
# Change to source directory
original_cwd = Path.cwd()
try:
import os
os.chdir(source_dir)
# Build wheel
wheel_name = build_api.build_wheel(str(output_dir))
print(f"Built wheel: {wheel_name}")
# Build source distribution
sdist_name = build_api.build_sdist(str(output_dir))
print(f"Built sdist: {sdist_name}")
return wheel_name, sdist_name
finally:
os.chdir(original_cwd)
# Usage
if __name__ == "__main__":
source = Path("./my-poetry-project")
dist = Path("./dist")
dist.mkdir(exist_ok=True)
wheel, sdist = build_project(source, dist)
``` { .api }
### Integration with Build Tools
```python
# pyproject.toml configuration for using Poetry Core backend
"""
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
"""
# Example using 'build' package
from pathlib import Path
import build
def build_with_frontend(project_path: Path, output_dir: Path):
"""Build using the 'build' package as frontend."""
builder = build.ProjectBuilder(project_path)
# Build wheel
wheel_path = builder.build("wheel", output_dir)
print(f"Wheel built: {wheel_path}")
# Build sdist
sdist_path = builder.build("sdist", output_dir)
print(f"Sdist built: {sdist_path}")
return wheel_path, sdist_path
``` { .api }
### Metadata Inspection
```python
import tempfile
from pathlib import Path
import poetry.core.masonry.api as build_api
def inspect_metadata(project_dir: Path):
"""Extract and inspect package metadata without full build."""
original_cwd = Path.cwd()
try:
import os
os.chdir(project_dir)
with tempfile.TemporaryDirectory() as temp_dir:
# Prepare metadata
metadata_name = build_api.prepare_metadata_for_build_wheel(temp_dir)
metadata_dir = Path(temp_dir) / metadata_name
# Read METADATA file
metadata_file = metadata_dir / "METADATA"
if metadata_file.exists():
print("Package Metadata:")
print(metadata_file.read_text())
# List all metadata files
print(f"\nMetadata files in {metadata_name}:")
for file in metadata_dir.iterdir():
print(f" {file.name}")
finally:
os.chdir(original_cwd)
``` { .api }
## Error Handling
### Common Exceptions
```python
from poetry.core.exceptions import (
PoetryCoreError,
PyProjectError,
ValidationError
)
def safe_build_wheel(wheel_dir: str):
"""Build wheel with comprehensive error handling."""
try:
return build_api.build_wheel(wheel_dir)
except PyProjectError as e:
print(f"PyProject configuration error: {e}")
# Handle invalid pyproject.toml
except ValidationError as e:
print(f"Project validation error: {e}")
# Handle schema validation failures
except PoetryCoreError as e:
print(f"Poetry Core error: {e}")
# Handle other Poetry-specific errors
except Exception as e:
print(f"Unexpected build error: {e}")
# Handle system/IO errors
return None
``` { .api }
## Build Backend Integration
### Frontend Compatibility
Poetry Core's build backend is compatible with:
- **pip** - `pip install .` or `pip wheel .`
- **build** - `python -m build`
- **PyPA/build** - Programmatic building
- **tox** - Automated testing with different environments
- **cibuildwheel** - Cross-platform wheel building
- **setuptools-scm** - Version from VCS tags (with configuration)
### Performance Considerations
```python
# For better performance in CI/CD:
config_settings = {
# Skip tests during wheel building
"--skip-tests": "true",
# Use faster compression
"--wheel-compression": "deflate",
# Parallel processing when supported
"--parallel": "auto"
}
# Note: Actual support depends on Poetry Core version
wheel = build_api.build_wheel("./dist", config_settings=config_settings)
``` { .api }
## Type Definitions
```python
from typing import Any
# Configuration settings type
ConfigSettings = dict[str, Any] | None
# Return types
RequirementsList = list[str]
FileName = str
MetadataDirectoryName = str
``` { .api }
## Debugging and Logging
```python
import logging
# Enable Poetry Core debug logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("poetry.core")
# The build backend will log detailed information about:
# - Project discovery and validation
# - Dependency resolution
# - File collection and processing
# - Build artifact creation
``` { .api }Install with Tessl CLI
npx tessl i tessl/pypi-poetry-core