CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-setuptools

Easily download, build, install, upgrade, and uninstall Python packages

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception hierarchy for error handling in setuptools operations, including both setuptools-specific errors and re-exported distutils errors for compatibility. These exceptions provide detailed error information for debugging and handling package building issues.

Capabilities

Setuptools Warnings

Warning classes for deprecation notices and non-fatal issues.

class SetuptoolsDeprecationWarning(UserWarning):
    """
    Base class for setuptools deprecation warnings.

    Enhanced deprecation warning with better formatting and
    contextual information about deprecated functionality.

    This warning is raised when setuptools features are used
    that will be removed in future versions.
    """

Core Setuptools Errors

Primary exception classes for setuptools-specific errors.

class BaseError(Exception):
    """
    Root error class for all setuptools errors.

    This is an alias to distutils.errors.DistutilsError for
    compatibility and provides the base for setuptools exceptions.
    """

class InvalidConfigError(BaseError):
    """
    Exception raised for invalid configuration.

    Raised when configuration files (setup.cfg, pyproject.toml)
    contain invalid values, syntax errors, or incompatible options.

    Common scenarios:
    - Invalid setup.cfg syntax
    - Incompatible configuration values
    - Missing required configuration sections
    - Invalid pyproject.toml structure
    """

class RemovedConfigError(BaseError):
    """
    Exception raised when using removed or deprecated configuration.

    Raised when configuration options that have been removed from
    setuptools are still used in configuration files.

    Common scenarios:
    - Using deprecated setup.cfg options
    - Obsolete command configuration
    - Removed metadata fields
    """

class RemovedCommandError(BaseError):
    """
    Exception raised when using removed setuptools commands.

    Raised when attempting to use setuptools commands that have
    been removed or deprecated.

    Common scenarios:
    - Using removed command classes
    - Attempting to run obsolete commands
    - Deprecated command-line options
    """

class PackageDiscoveryError(BaseError):
    """
    Exception raised during package discovery.

    Raised when find_packages() or related functions encounter
    issues while discovering packages in the source tree.

    Common scenarios:
    - Circular imports during discovery
    - Invalid package structure
    - Permission issues accessing directories
    - Conflicting package names
    """

Build Backend Errors

Errors specific to the PEP 517/518 build backend functionality.

class SetupRequirementsError(BaseError):
    """
    Exception raised when setup requirements cannot be satisfied.

    Raised by the build backend when dependencies needed for building
    the package cannot be installed or are incompatible.

    Attributes:
    - specifiers (list): List of requirement specifiers that failed
    """

    def __init__(self, specifiers):
        """
        Initialize with failed requirement specifiers.

        Parameters:
        - specifiers (list): Requirements that could not be satisfied
        """
        self.specifiers = specifiers
        super().__init__(f"Could not satisfy requirements: {specifiers}")

Distutils Error Re-exports

Setuptools re-exports all distutils errors for compatibility, allowing code to import errors from setuptools instead of distutils.

class DistutilsError(Exception):
    """Base class for distutils errors."""

class DistutilsModuleError(DistutilsError):
    """Module-related errors."""

class DistutilsClassError(DistutilsError):
    """Class-related errors."""

class DistutilsGetoptError(DistutilsError):
    """Command-line option parsing errors."""

class DistutilsArgError(DistutilsError):
    """Invalid argument errors."""

class DistutilsFileError(DistutilsError):
    """File operation errors."""

class DistutilsOptionError(DistutilsError):
    """Invalid option errors."""

class DistutilsSetupError(DistutilsError):
    """Setup configuration errors."""

class DistutilsPlatformError(DistutilsError):
    """Platform-specific errors."""

class DistutilsExecError(DistutilsError):
    """Command execution errors."""

class DistutilsInternalError(DistutilsError):
    """Internal setuptools/distutils errors."""

class DistutilsTemplateError(DistutilsError):
    """Template processing errors."""

class DistutilsByteCompileError(DistutilsError):
    """Python bytecode compilation errors."""

# Compilation and linking errors
class CCompilerError(Exception):
    """C compiler errors."""

class PreprocessError(CCompilerError):
    """Preprocessor errors."""

class CompileError(CCompilerError):
    """Compilation errors."""

class LibError(CCompilerError):
    """Library creation errors."""

class LinkError(CCompilerError):
    """Linking errors."""

class UnknownFileError(CCompilerError):
    """Unknown file type errors."""

Usage Examples

Basic Error Handling

from setuptools import setup, find_packages
from setuptools.errors import (
    InvalidConfigError,
    PackageDiscoveryError,
    SetupRequirementsError
)

try:
    packages = find_packages()
    setup(
        name='my-package',
        packages=packages,
        # ... other configuration
    )
except PackageDiscoveryError as e:
    print(f"Could not discover packages: {e}")
    # Handle package discovery issues
except InvalidConfigError as e:
    print(f"Invalid configuration: {e}")
    # Handle configuration errors
except Exception as e:
    print(f"Setup failed: {e}")
    raise

Build Backend Error Handling

from setuptools.build_meta import build_wheel, SetupRequirementsError

def safe_build_wheel(wheel_directory, config_settings=None):
    """Safely build a wheel with error handling."""
    try:
        return build_wheel(wheel_directory, config_settings)
    except SetupRequirementsError as e:
        print(f"Missing build requirements: {e.specifiers}")
        # Could install requirements and retry
        raise
    except Exception as e:
        print(f"Build failed: {e}")
        raise

Warning Handling

import warnings
from setuptools.warnings import SetuptoolsDeprecationWarning

# Filter setuptools deprecation warnings
warnings.filterwarnings('ignore', category=SetuptoolsDeprecationWarning)

# Or handle them explicitly
def handle_setuptools_warnings():
    """Custom handler for setuptools warnings."""
    warnings.filterwarnings(
        'error',  # Convert to exception
        category=SetuptoolsDeprecationWarning
    )
    
    try:
        # Some setuptools operation that might warn
        from setuptools import setup
        setup(
            name='my-package',
            # ... configuration that might use deprecated features
        )
    except SetuptoolsDeprecationWarning as w:
        print(f"Deprecated feature used: {w}")
        # Update configuration to remove deprecated usage

Custom Command Error Handling

from setuptools import Command
from setuptools.errors import DistutilsSetupError, DistutilsExecError

class CustomCommand(Command):
    """Custom command with proper error handling."""
    
    description = 'Custom command with error handling'
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        # Validate options
        if not hasattr(self, 'required_option'):
            raise DistutilsSetupError('required_option must be set')

    def run(self):
        try:
            # Command implementation
            self.execute_custom_logic()
        except subprocess.CalledProcessError as e:
            raise DistutilsExecError(f'Command failed: {e}') from e
        except FileNotFoundError as e:
            raise DistutilsFileError(f'Required file not found: {e}') from e

    def execute_custom_logic(self):
        """Custom command logic that might fail."""
        pass

Extension Build Error Handling

from setuptools import setup, Extension
from setuptools.errors import CCompilerError, CompileError

def build_extensions_safely():
    """Build extensions with proper error handling."""
    extensions = [
        Extension(
            'my_package.fast_module',
            sources=['src/fast_module.c'],
        )
    ]
    
    try:
        setup(
            name='my-package',
            ext_modules=extensions,
        )
    except CCompilerError as e:
        print(f"Compiler error: {e}")
        # Could fall back to pure Python implementation
        setup(
            name='my-package',
            # Setup without extensions
        )
    except CompileError as e:
        print(f"Compilation failed: {e}")
        # Handle compilation failure
        raise

Configuration Error Recovery

from setuptools import setup
from setuptools.errors import InvalidConfigError, RemovedConfigError

def setup_with_fallback():
    """Setup with configuration error recovery."""
    try:
        # Try modern configuration
        setup(
            name='my-package',
            # Modern setuptools configuration
        )
    except RemovedConfigError as e:
        print(f"Using deprecated configuration: {e}")
        # Fall back to alternative configuration
        setup(
            name='my-package',
            # Alternative configuration without deprecated features
        )
    except InvalidConfigError as e:
        print(f"Invalid configuration: {e}")
        # Provide helpful error message and fix suggestions
        print("Please check your setup.cfg or pyproject.toml for errors")
        raise

Comprehensive Error Handling

from setuptools import setup, find_packages
from setuptools.errors import *
import logging

def robust_setup():
    """Setup with comprehensive error handling."""
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    try:
        packages = find_packages()
        logger.info(f"Found packages: {packages}")
        
        setup(
            name='my-package',
            version='1.0.0',
            packages=packages,
            # ... other configuration
        )
        logger.info("Setup completed successfully")
        
    except PackageDiscoveryError as e:
        logger.error(f"Package discovery failed: {e}")
        # Could manually specify packages as fallback
        raise
        
    except InvalidConfigError as e:
        logger.error(f"Configuration error: {e}")
        # Log detailed error information
        raise
        
    except SetupRequirementsError as e:
        logger.error(f"Build requirements not satisfied: {e.specifiers}")
        # Could attempt to install requirements
        raise
        
    except DistutilsError as e:
        logger.error(f"Distutils error: {e}")
        # Handle general distutils errors
        raise
        
    except Exception as e:
        logger.error(f"Unexpected error during setup: {e}")
        # Log full traceback for debugging
        logger.exception("Full traceback:")
        raise

if __name__ == '__main__':
    robust_setup()

Install with Tessl CLI

npx tessl i tessl/pypi-setuptools

docs

build-backend.md

commands.md

core-classes.md

core-setup.md

exceptions.md

index.md

pkg-resources.md

utilities.md

tile.json