Poetry PEP 517 Build Backend for building Python packages with lightweight, compliant, self-contained build system
—
Comprehensive JSON schema validation for Poetry configuration files and internal data structures. Poetry Core uses JSON schemas to validate pyproject.toml configurations and ensure data integrity.
from poetry.core.json import validate_object, ValidationError
``` { .api }
## Capabilities
### Object Validation
Validates Python dictionaries against predefined JSON schemas for Poetry configuration.
```python { .api }
def validate_object(obj: dict[str, Any], schema_name: str) -> list[str]:
"""
Validate a Python object against a JSON schema.
Args:
obj: Dictionary to validate
schema_name: Name of schema file (without .json extension)
Returns:
List of validation error messages. Empty list if valid.
Raises:
ValueError: If schema file does not exist
Available Schemas:
- "poetry-schema": Validates [tool.poetry] configuration
- "project-schema": Validates [project] PEP 621 configuration
"""class ValidationError(ValueError):
"""
Exception raised for JSON schema validation failures.
Inherits from ValueError and provides additional context
for schema validation errors.
"""from poetry.core.json import validate_object, ValidationError
from poetry.core.pyproject.toml import PyProjectTOML
from pathlib import Path
# Load pyproject.toml
pyproject_path = Path("pyproject.toml")
pyproject = PyProjectTOML(pyproject_path)
# Validate Poetry configuration section
poetry_config = pyproject.poetry_config
errors = validate_object(poetry_config, "poetry-schema")
if errors:
print("Poetry configuration errors:")
for error in errors:
print(f" - {error}")
else:
print("Poetry configuration is valid")from poetry.core.json import validate_object
from poetry.core.pyproject.toml import PyProjectTOML
from pathlib import Path
# Load and validate PEP 621 [project] section
pyproject = PyProjectTOML(Path("pyproject.toml"))
# Get project configuration if present
if "project" in pyproject.data:
project_config = pyproject.data["project"]
errors = validate_object(project_config, "project-schema")
if errors:
print("Project configuration errors:")
for error in errors:
print(f" - {error}")
else:
print("Project configuration is valid")from poetry.core.json import validate_object, ValidationError
# Example of handling validation with try/catch
try:
config = {
"name": "my-package",
"version": "1.0.0",
# Missing required fields or invalid structure
}
errors = validate_object(config, "poetry-schema")
if errors:
# Create ValidationError with detailed message
error_message = "Configuration validation failed:\n" + "\n".join(errors)
raise ValidationError(error_message)
except ValidationError as e:
print(f"Validation failed: {e}")
except ValueError as e:
print(f"Schema error: {e}")from poetry.core.json import validate_object
from typing import Any
def validate_poetry_config(config: dict[str, Any]) -> bool:
"""
Helper function to validate Poetry configuration.
Args:
config: Poetry configuration dictionary
Returns:
True if valid, False otherwise
"""
try:
errors = validate_object(config, "poetry-schema")
return len(errors) == 0
except ValueError:
# Schema not found or other validation setup error
return False
# Usage
config = {
"name": "my-package",
"version": "1.0.0",
"description": "A sample package"
}
if validate_poetry_config(config):
print("Configuration is valid")
else:
print("Configuration has errors")Poetry Core includes two main JSON schemas:
poetry-schema)Validates the [tool.poetry] section of pyproject.toml files. This schema ensures:
name, version, descriptionauthors, maintainers, license, readme, etc.dependencies and group sectionspackages, include, exclude configurationskeywords, classifiers, urlsproject-schema)Validates PEP 621 [project] section configuration. This schema ensures:
name, version, description, authorsThe JSON validation integrates seamlessly with Poetry Core's configuration system:
from poetry.core.factory import Factory
from poetry.core.pyproject.toml import PyProjectTOML
from pathlib import Path
# Factory validation includes JSON schema validation
project_path = Path("/path/to/project")
pyproject = PyProjectTOML(project_path / "pyproject.toml")
# Validate entire configuration
validation_errors = Factory.validate(pyproject.data)
if validation_errors:
for section, errors in validation_errors.items():
print(f"Errors in [{section}]:")
for error in errors:
print(f" - {error}")The validation system uses fastjsonschema for high-performance validation:
# Validate configuration immediately after loading
pyproject = PyProjectTOML(path)
errors = validate_object(pyproject.poetry_config, "poetry-schema")
if errors:
raise ValidationError(f"Invalid configuration: {errors}")try:
errors = validate_object(config, "custom-schema")
except ValueError as e:
if "does not exist" in str(e):
print("Schema not available, skipping validation")
else:
raisedef format_validation_errors(errors: list[str]) -> str:
"""Format validation errors for user display."""
if not errors:
return "Configuration is valid"
formatted = "Configuration validation failed:\n"
for i, error in enumerate(errors, 1):
formatted += f" {i}. {error}\n"
return formatted.strip()Install with Tessl CLI
npx tessl i tessl/pypi-poetry-core