CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-poetry-core

Poetry PEP 517 Build Backend for building Python packages with lightweight, compliant, self-contained build system

Pending
Overview
Eval results
Files

json-validation.mddocs/

JSON Schema Validation

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.

Core Import

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
    """

Validation Exception

class ValidationError(ValueError):
    """
    Exception raised for JSON schema validation failures.
    
    Inherits from ValueError and provides additional context
    for schema validation errors.
    """

Usage Examples

Validating Poetry Configuration

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")

Validating PEP 621 Project Configuration

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")

Error Handling with ValidationError

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}")

Custom Validation Function

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")

Available Schemas

Poetry Core includes two main JSON schemas:

1. Poetry Schema (poetry-schema)

Validates the [tool.poetry] section of pyproject.toml files. This schema ensures:

  • Required fields: name, version, description
  • Optional fields: authors, maintainers, license, readme, etc.
  • Dependencies: Proper structure for dependencies and group sections
  • Build settings: Valid packages, include, exclude configurations
  • Metadata: Valid keywords, classifiers, urls

2. Project Schema (project-schema)

Validates PEP 621 [project] section configuration. This schema ensures:

  • Core metadata: name, version, description, authors
  • Dependencies: PEP 508 dependency specifications
  • Optional dependencies: Extra groups and optional dependency sets
  • Classifiers: Valid PyPI trove classifiers
  • URLs: Project homepage, repository, documentation links

Schema Integration

The 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}")

Internal Implementation

The validation system uses fastjsonschema for high-performance validation:

  • Fast compilation: Schemas are compiled to Python functions
  • Detailed errors: Provides specific error messages with field paths
  • Schema loading: Automatically loads schemas from internal resources
  • Error formatting: Converts JSON schema errors to readable messages

Best Practices

1. Validate Early

# Validate configuration immediately after loading
pyproject = PyProjectTOML(path)
errors = validate_object(pyproject.poetry_config, "poetry-schema")
if errors:
    raise ValidationError(f"Invalid configuration: {errors}")

2. Handle Missing Schemas Gracefully

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:
        raise

3. Provide User-Friendly Error Messages

def 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

docs

build-backend.md

builders.md

configuration.md

constraints.md

factory-core.md

index.md

json-validation.md

packages.md

utilities.md

vcs-support.md

version-system.md

tile.json