CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-absl-py

Abseil Python Common Libraries providing application startup utilities, command-line flag management, enhanced logging, and comprehensive testing utilities.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

app.mddocs/

Application Startup

Application lifecycle management providing the main entry point for absl-based Python applications. Handles automatic flag parsing, exception handling, initialization callbacks, and proper program termination.

Capabilities

Main Application Runner

The primary entry point for absl applications that automatically parses command-line flags, handles exceptions, and manages the application lifecycle.

def run(main, argv=None, flags_parser=parse_flags_with_usage):
    """
    Run the main function with automatic flag parsing and exception handling.
    
    This function serves as the entry point for absl applications. It automatically
    parses command-line flags, calls initialization callbacks, handles exceptions,
    and ensures proper program termination.
    
    Args:
        main: Main function that takes argv as its single argument
        argv: Command line arguments (defaults to sys.argv if None)
        flags_parser: Function to parse flags (defaults to parse_flags_with_usage)
    
    The main function should have signature: main(argv: List[str]) -> None
    """

Usage and Help

Functions for displaying usage information and handling help requests.

def usage(shorthelp=False, writeto_stdout=False, detailed_error=None, exitcode=None):
    """
    Write usage information to stderr and optionally exit.
    
    Args:
        shorthelp (bool): If True, print short help instead of full help
        writeto_stdout (bool): If True, write to stdout instead of stderr  
        detailed_error (str): Detailed error message to include in output
        exitcode (int): Exit code to use when exiting (if None, don't exit)
    """

Initialization Callbacks

Register callbacks to be executed after flag parsing but before the main function.

def call_after_init(callback):
    """
    Register a callback to be called after flag parsing.
    
    Callbacks are executed in the order they were registered, after flags
    have been parsed but before the main function is called.
    
    Args:
        callback: Function to call after initialization, takes no arguments
    """

Exception Handling

Custom exception types and exception handler registration for application-specific error handling.

class Error(Exception):
    """Base exception class for the app module."""

class UsageError(Error):
    """
    Exception indicating a usage error (bad command-line arguments).
    
    When raised in the main function, automatically displays usage
    information and exits with code 1.
    """

def install_exception_handler(handler):
    """
    Install a custom exception handler.
    
    Args:
        handler: ExceptionHandler instance or callable that takes an exception
    """

class ExceptionHandler:
    """
    Base class for custom exception handlers.
    
    Subclass this to create custom exception handling behavior.
    """
    
    def wants(self, exc):
        """
        Determine if this handler wants to handle an exception.
        
        Args:
            exc: The exception to potentially handle
            
        Returns:
            bool: True if this handler wants to handle the exception
        """
    
    def handle(self, exc):
        """
        Handle an exception.
        
        Args:
            exc: The exception to handle
            
        Returns:
            bool: True if the exception was handled, False otherwise
        """

Flag Integration

Functions for integrating with the flags system, including help flag definitions and flag parsing with usage error handling.

def parse_flags_with_usage(args):
    """
    Parse flags and display usage on error.
    
    Args:
        args: Command-line arguments to parse
        
    Returns:
        List of remaining non-flag arguments
        
    Raises:
        SystemExit: On flag parsing errors with usage information
    """

def define_help_flags():
    """Define standard help flags (--help, --helpshort, --helpfull, --helpxml)."""

# Help flag classes for advanced usage
class HelpFlag(flags.BooleanFlag):
    """Special boolean flag that displays usage and raises SystemExit."""
    NAME = 'help'
    SHORT_NAME = '?'

class HelpshortFlag(HelpFlag):
    """Flag for displaying short help information."""
    NAME = 'helpshort'

class HelpfullFlag(flags.BooleanFlag):
    """Flag for displaying full help information."""
    NAME = 'helpfull'

class HelpXMLFlag(flags.BooleanFlag):
    """Flag for displaying help in XML format."""
    NAME = 'helpxml'

Usage Examples

Basic Application Structure

from absl import app
from absl import flags
from absl import logging

FLAGS = flags.FLAGS
flags.DEFINE_string('input_file', None, 'Input file to process.')
flags.DEFINE_boolean('verbose', False, 'Enable verbose output.')

def main(argv):
    if len(argv) > 1:
        raise app.UsageError('Too many command-line arguments.')
    
    if FLAGS.verbose:
        logging.set_verbosity(logging.DEBUG)
    
    if FLAGS.input_file is None:
        raise app.UsageError('--input_file is required.')
    
    # Application logic here
    logging.info('Processing file: %s', FLAGS.input_file)

if __name__ == '__main__':
    app.run(main)

Custom Exception Handling

from absl import app
import logging

class CustomExceptionHandler(app.ExceptionHandler):
    def handle(self, exc):
        if isinstance(exc, FileNotFoundError):
            logging.error('File not found: %s', exc.filename)
            return True  # Exception handled
        return False  # Not handled

def main(argv):
    app.install_exception_handler(CustomExceptionHandler())
    # Application logic that might raise FileNotFoundError

if __name__ == '__main__':
    app.run(main)

Initialization Callbacks

from absl import app
from absl import flags
import logging

FLAGS = flags.FLAGS
flags.DEFINE_string('config_file', None, 'Configuration file.')

def initialize_config():
    """Initialize configuration after flags are parsed."""
    if FLAGS.config_file:
        logging.info('Loading config from: %s', FLAGS.config_file)
        # Load configuration logic here

def main(argv):
    # Configuration is already loaded via callback
    logging.info('Starting application with loaded config.')

if __name__ == '__main__':
    app.call_after_init(initialize_config)
    app.run(main)

Install with Tessl CLI

npx tessl i tessl/pypi-absl-py

docs

app.md

flags.md

index.md

logging.md

testing.md

tile.json