Consider absl Python library to work with flags

Artem Rys
python4you
Published in
2 min readDec 25, 2019

--

Photo by Joshua Fuller on Unsplash

I have been writing a small scraping application these days. I wanted it to send metrics and use chromedriver. I also wanted to be able to run it locally and don’t send metrics while running locally. So, I needed some way to separate local and production environments. The easiest way to do that — use flags.

My options:

  • optparse — deprecated
  • argparse — builtin Python library to deal with flags
  • abseil — an open-source library from Google

That time I did not know anything about abseil, so my only choice was to use argparse. That’s what I have got with it.

import argparseparser = argparse.ArgumentParser()
dry_run_parser = parser.add_mutually_exclusive_group(required=True)
dry_run_parser.add_argument("--dry_run", dest="dry_run", action="store_true")
dry_run_parser.add_argument("--nodry_run", dest="dry_run", action="store_false")
parser.add_argument("--chromedriver_path", type=str)

And this is code with absl library usage.

from absl import flagsFLAGS = flags.FLAGS
flags.DEFINE_bool("dry_run", False, help="If True don't write metrics")
flags.DEFINE_string("chromedriver_path", "/usr/bin/chromedriver", help="Path to chromedriver executable")

--

--

Artem Rys
python4you

Principal Software Engineer @ Splunk. Writing about Python, GitHub and Splunk.