Abseil Python Common Libraries

2.4.0 · active · verified Sat Mar 28

absl-py is a collection of Python library code for building Python applications, originating from Google's internal codebase. It provides essential utilities for application startup, a distributed command-line flags system, a custom logging module, and testing utilities. The library is actively maintained, with frequent releases, and is currently at version 2.4.0.

Warnings

Install

Imports

Quickstart

This example demonstrates defining and using command-line flags, basic logging, and integrating with `absl.app.run()` to handle program execution. You can run this script and pass flags like `--greeting_target=Pythonista` or `--repeat_count=5`. The `os.environ` usage is for demonstrating how to programmatically set flags, especially useful in testing contexts where direct command-line arguments might not be feasible.

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

FLAGS = flags.FLAGS

flags.DEFINE_string('greeting_target', 'World', 'The entity to greet.')
flags.DEFINE_integer('repeat_count', 1, 'How many times to repeat the greeting.', lower_bound=1)
flags.DEFINE_boolean('verbose', False, 'If true, print verbose output.')

def main(argv):
  if FLAGS.verbose:
    logging.set_verbosity(logging.DEBUG)
    logging.debug('Verbose mode enabled. Non-flag arguments: %s', argv[1:])
  else:
    logging.set_verbosity(logging.INFO)

  for _ in range(FLAGS.repeat_count):
    logging.info('Hello, %s!', FLAGS.greeting_target)
  
  # Example of an argument passed directly, not as a flag
  if len(argv) > 1:
    logging.warning('Unrecognized positional arguments: %s', argv[1:])

if __name__ == '__main__':
  # To run: python your_script.py --greeting_target=User --repeat_count=3 --verbose
  # Or with environment variable for testing:
  # os.environ['greeting_target'] = 'TestUser'
  # os.environ['repeat_count'] = '2'
  # Then run: python your_script.py --verbose
  app.run(main)

view raw JSON →