CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-poetry

Python dependency management and packaging made easy.

Pending
Overview
Eval results
Files

core-api.mddocs/

Core API

Core Poetry classes and factory methods for creating and managing Python projects programmatically. These components form the foundation of Poetry's functionality and provide the primary interfaces for programmatic usage.

Capabilities

Poetry Class

The central class representing a Poetry project, providing access to all project-related functionality including configuration, dependencies, build system, and metadata.

class Poetry:
    """
    Main Poetry project representation extending poetry-core functionality.
    
    Provides access to project configuration, dependencies, lock file management,
    repository pools, and build system integration.
    """
    VERSION: str  # Poetry version
    
    def __init__(self, file: Path, local_config: dict, package: ProjectPackage, 
                 locker: Locker, config: Config, disable_cache: bool = False):
        """
        Initialize Poetry instance.
        
        Args:
            file: Path to pyproject.toml file
            local_config: Project-specific configuration
            package: Project package metadata
            locker: Lock file manager
            config: Global configuration
            disable_cache: Whether to disable caching
        """
    
    @property
    def pyproject(self) -> PyProjectTOML:
        """Access to enhanced pyproject.toml handler."""
    
    @property
    def file(self) -> TOMLFile:
        """Access to pyproject.toml file handler."""
    
    @property
    def locker(self) -> Locker:
        """Access to lock file manager."""
    
    @property
    def pool(self) -> RepositoryPool:
        """Access to repository pool for package sources."""
    
    @property
    def config(self) -> Config:
        """Access to configuration manager."""
    
    @property
    def disable_cache(self) -> bool:
        """Whether caching is disabled."""
    
    def set_locker(self, locker: Locker) -> Poetry:
        """
        Configure lock file handler.
        
        Args:
            locker: Lock file manager instance
            
        Returns:
            Self for method chaining
        """
    
    def set_pool(self, pool: RepositoryPool) -> Poetry:
        """
        Set repository pool for package sources.
        
        Args:
            pool: Repository pool instance
            
        Returns:
            Self for method chaining
        """
    
    def set_config(self, config: Config) -> Poetry:
        """
        Set configuration manager.
        
        Args:
            config: Configuration instance
            
        Returns:
            Self for method chaining
        """
    
    def get_sources(self) -> list[Source]:
        """
        Get configured package sources from pyproject.toml.
        
        Returns:
            List of configured package sources
        """

Usage Example

from poetry.factory import Factory
from pathlib import Path

# Create Poetry instance
poetry = Factory().create_poetry(cwd=Path("/path/to/project"))

# Access project information
print(f"Project: {poetry.package.name} v{poetry.package.version}")
print(f"Poetry version: {poetry.VERSION}")

# Check if project is locked
if poetry.locker.is_locked():
    print("Project has lock file")
    
# Get package sources
sources = poetry.get_sources()
for source in sources:
    print(f"Source: {source.name} -> {source.url}")

Factory Class

Factory class for creating Poetry instances and related components. Provides the primary entry points for programmatic Poetry usage.

class Factory:
    """
    Factory for creating Poetry instances and components.
    
    Handles discovery of Poetry projects, validation of configuration,
    and creation of properly configured Poetry instances.
    """
    
    def create_poetry(self, cwd: Path = None, with_groups: bool = True, 
                     io = None, disable_plugins: bool = False, 
                     disable_cache: bool = False) -> Poetry:
        """
        Create Poetry instance from project directory.
        
        Args:
            cwd: Project directory path (default: current directory)
            with_groups: Whether to include dependency groups
            io: IO interface for output
            disable_plugins: Whether to disable plugin loading
            disable_cache: Whether to disable caching
            
        Returns:
            Configured Poetry instance
            
        Raises:
            PoetryError: If pyproject.toml not found or invalid
        """
    
    def create_pool(self, config: Config, sources = None, io = None, 
                   disable_cache: bool = False) -> RepositoryPool:
        """
        Create repository pool for package sources.
        
        Args:
            config: Configuration instance
            sources: Optional list of package sources
            io: IO interface for output
            disable_cache: Whether to disable caching
            
        Returns:
            Configured repository pool
        """
    
    def create_package_source(self, source: dict, config: Config, 
                             disable_cache: bool = False):
        """
        Create package source from configuration.
        
        Args:
            source: Source configuration dictionary
            config: Configuration instance
            disable_cache: Whether to disable caching
            
        Returns:
            Package source instance
        """
    
    def create_pyproject_from_package(self, package) -> dict:
        """
        Generate pyproject.toml data from package metadata.
        
        Args:
            package: Package instance
            
        Returns:
            Dictionary containing pyproject.toml data
        """
    
    def validate(self, toml_data: dict, strict: bool = False) -> dict:
        """
        Validate Poetry configuration against schema.
        
        Args:
            toml_data: TOML configuration data
            strict: Whether to use strict validation
            
        Returns:
            Validated configuration data
            
        Raises:
            PoetryError: If validation fails
        """

Usage Example

from poetry.factory import Factory
from poetry.config.config import Config
from pathlib import Path

factory = Factory()

# Create Poetry instance from current directory
poetry = factory.create_poetry()

# Create Poetry instance from specific directory
poetry = factory.create_poetry(
    cwd=Path("/path/to/project"),
    disable_cache=True
)

# Create repository pool
config = Config.create()
pool = factory.create_pool(config)

# Validate configuration
toml_data = {
    "tool": {
        "poetry": {
            "name": "my-project",
            "version": "1.0.0",
            "description": "My project description"
        }
    }
}
validated_data = factory.validate(toml_data)

Project Discovery

Helper functions for discovering and working with Poetry projects.

def locate_config_file(cwd: Path = None) -> Path:
    """
    Locate pyproject.toml file in directory hierarchy.
    
    Args:
        cwd: Starting directory (default: current directory)
        
    Returns:
        Path to pyproject.toml file
        
    Raises:
        PoetryError: If no pyproject.toml found
    """

def validate_pyproject_file(file_path: Path) -> dict:
    """
    Validate pyproject.toml file contains Poetry configuration.
    
    Args:
        file_path: Path to pyproject.toml file
        
    Returns:
        Parsed TOML data
        
    Raises:
        PoetryError: If file invalid or missing Poetry section
    """

Integration Patterns

Context Manager Usage

from poetry.factory import Factory
from pathlib import Path

def with_poetry_project(project_path: Path):
    """Example context manager pattern for Poetry projects."""
    poetry = Factory().create_poetry(cwd=project_path)
    try:
        yield poetry
    finally:
        # Cleanup if needed
        pass

# Usage
with with_poetry_project(Path("/path/to/project")) as poetry:
    print(f"Working with {poetry.package.name}")
    # Perform operations

Dependency Analysis

from poetry.factory import Factory

def analyze_project_dependencies(project_path):
    """Analyze project dependencies."""
    poetry = Factory().create_poetry(cwd=project_path)
    
    # Get all dependencies
    dependencies = poetry.package.all_requires
    
    print(f"Project: {poetry.package.name}")
    print(f"Dependencies: {len(dependencies)}")
    
    for dep in dependencies:
        print(f"  {dep.name}: {dep.constraint}")
        
    # Check lock file status
    if poetry.locker.is_locked() and poetry.locker.is_fresh():
        print("Lock file is up to date")
    else:
        print("Lock file needs update")

Error Handling

The core API raises specific exceptions for different error conditions:

class PoetryError(Exception):
    """Base exception for Poetry-specific errors."""

class InvalidProjectError(PoetryError):
    """Raised when project configuration is invalid."""

class ProjectNotFoundError(PoetryError):
    """Raised when Poetry project cannot be found."""

Common error scenarios include:

  • Missing or invalid pyproject.toml files
  • Projects without Poetry configuration section
  • Invalid dependency specifications
  • Circular dependency detection
  • Configuration validation failures

Install with Tessl CLI

npx tessl i tessl/pypi-poetry

docs

build-system.md

cli-commands.md

configuration.md

core-api.md

environment.md

index.md

installation.md

package-management.md

plugins.md

tile.json