Abseil Python Common Libraries providing application startup utilities, command-line flag management, enhanced logging, and comprehensive testing utilities.
npx @tessl/cli install tessl/pypi-absl-py@2.3.0Abseil Python Common Libraries is a collection of Python library code for building Python applications. The code is collected from Google's own Python code base and has been extensively tested and used in production. It provides four main components: simple application startup utilities, a distributed command-line flags system, enhanced logging functionality, and comprehensive testing utilities.
pip install absl-pyfrom absl import app
from absl import flags
from absl import logging
from absl.testing import absltestIndividual module imports:
# Application startup
from absl import app
# Command-line flags
from absl import flags
FLAGS = flags.FLAGS
# Enhanced logging
from absl import logging
# Testing utilities
from absl.testing import absltest
from absl.testing import parameterized
from absl.testing import flagsaverfrom absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
# Define command-line flags
flags.DEFINE_string('name', 'World', 'Name to greet.')
flags.DEFINE_integer('count', 1, 'Number of greetings.')
flags.DEFINE_boolean('verbose', False, 'Enable verbose logging.')
def main(argv):
"""Main application entry point."""
del argv # Unused.
# Configure logging based on flags
if FLAGS.verbose:
logging.set_verbosity(logging.DEBUG)
# Use logging instead of print
logging.info('Starting application...')
# Access flag values
for i in range(FLAGS.count):
logging.info('Hello, %s! (greeting %d/%d)', FLAGS.name, i+1, FLAGS.count)
logging.info('Application completed.')
if __name__ == '__main__':
app.run(main)The absl-py library is organized around four core modules that work together:
This design enables modular Python applications where configuration, logging, and testing are consistently handled across all components.
Application lifecycle management with automatic flag parsing, exception handling, and proper program termination. Provides the main entry point for absl-based applications.
def run(main, argv=None, flags_parser=parse_flags_with_usage):
"""
Run the main function with automatic flag parsing and exception handling.
Args:
main: Main function that takes argv as argument
argv: Command line arguments (defaults to sys.argv)
flags_parser: Function to parse flags (defaults to parse_flags_with_usage)
"""
class UsageError(Exception):
"""Exception for usage/argument errors."""
def call_after_init(callback):
"""Register callback to run after initialization."""Distributed flag definition system allowing any module to define command-line flags. Supports various flag types, validation, and help generation with global flag registry.
def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
"""Define a string flag."""
def DEFINE_boolean(name, default, help, flag_values=flags.FLAGS, **args):
"""Define a boolean flag."""
def DEFINE_integer(name, default, help, flag_values=flags.FLAGS, **args):
"""Define an integer flag."""
def DEFINE_float(name, default, help, flag_values=flags.FLAGS, **args):
"""Define a float flag."""
def DEFINE_enum(name, default, enum_values, help, flag_values=flags.FLAGS, **args):
"""Define an enum flag."""
FLAGS: FlagValues # Global flag registryComprehensive logging functionality built on Python's standard logging with additional features like verbosity control, conditional logging, and structured output formatting.
def info(msg, *args, **kwargs):
"""Log an info message."""
def warning(msg, *args, **kwargs):
"""Log a warning message."""
def error(msg, *args, **kwargs):
"""Log an error message."""
def fatal(msg, *args, **kwargs):
"""Log a fatal message and exit."""
def debug(msg, *args, **kwargs):
"""Log a debug message."""
def set_verbosity(v):
"""Set logging verbosity level."""
def get_verbosity():
"""Get current verbosity level."""
def vlog(level, msg, *args, **kwargs):
"""Log a verbose message at the specified level."""
def log_every_n(level, msg, n, *args, **kwargs):
"""Log a message every N times this function is called."""
def log_every_n_seconds(level, msg, n_seconds, *args, **kwargs):
"""Log a message at most once every N seconds."""Comprehensive testing framework extending unittest with additional assertions, parameterized testing, temporary file management, and flag state management for tests.
class TestCase(unittest.TestCase):
"""Enhanced test case with additional assertions and utilities."""
def main(*args, **kwargs):
"""Main test runner entry point."""
class TempFileCleanup(enum.Enum):
"""Enum for temporary file cleanup behavior."""
ALWAYS = 'always'
SUCCESS = 'success'
FAILURE = 'failure'absl-py defines several exception types for different error conditions:
# Application errors
class app.Error(Exception):
"""Base application exception."""
class app.UsageError(app.Error):
"""Usage/argument error exception."""
# Flag errors
class flags.Error(Exception):
"""Base flag exception."""
class flags.ValidationError(flags.Error):
"""Flag validation error."""
class flags.UnrecognizedFlagError(flags.Error):
"""Unrecognized flag error."""Common error handling patterns involve catching specific exceptions and providing user-friendly error messages while maintaining proper exit codes.