Abseil Python Common Libraries
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
- breaking Abseil Python has progressively dropped support for older Python versions. Version 2.4.0 dropped support for Python 3.8 and 3.9. Version 2.2.2 removed support for Python 3.7. Version 2.0.0 dropped support for Python 3.6.
- gotcha Directly evaluating `absl.flags.Flag` instances in a boolean context (e.g., `if FLAGS.myflag:`) will raise an error. This prevents accidental usage of the Flag object itself rather than its value.
- breaking The `absl.logging.exception` function's behavior regarding the `exc_info` argument changed in v2.0.0. Previously, passing `exc_info` could raise a `KeyError`. It now correctly accepts `exc_info` as an argument (with a default value of `True`).
- gotcha Flag names defined with `absl.flags.DEFINE_*` are globally registered. This means that if multiple modules or libraries define flags with the same name, a `DuplicateFlagError` will occur upon import or flag definition.
Install
-
pip install absl-py
Imports
- app
from absl import app
- flags
from absl import flags
- logging
from absl import logging
- absltest
from absl.testing import absltest
- flagsaver
from absl.testing import flagsaver
Quickstart
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)