serhii.net

In the middle of the desert you can say anything you want

24 Nov 2021

211124-1744 argparse notes

(Those too after a long talk to a colleague at work, this time #py/argparse)

Cool things about argparse:1

  • parser.add_argument('--two-words') would automatically map to args.two_words (_ vs -)!
  • One can provide complex types!2 For files, two options.
    • The first one allows to set file permissions etc., but it opens them and returns the handle to you, which you may not want.
    • pathlib.Path() works as expected, and even automagically parses string paths from args into the Path!
      • Additionally we can then establish that we’re working with Paths from the very beginning, getting rid of the str or Path ambiguity.
      • “Be strict and clear from the very beginning, then you don’t have to deal Path or str”

    • Sample of both from official documentation:
      parser.add_argument('a', type=argparse.FileType('w', encoding='latin-1'))
      parser.add_argument('b', type=pathlib.Path)
      
  • You can get defalut values from os.environ()! Then you can also run it as
    WHATVEER_VALUE=234 python3 file.py
    

A nice structure for it all is:

  1. if __name__ == '__main__': runs a function like main() getting rid of the scope issues
  2. Parsing is done my a separate function, that returns the Namespace:
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser()
        parser.add_argument('--input-directory' ..)
        return parser.parse_args()
    
  3. Then in main() we use it like args = parse_args(); if args.input_directory == ... This is nice also because then we don’t have to deal with an arparse object in main, just its results.

Also, in general, CLI programs have arguments like program --arg-one, not program --arg_one. I write the latter one because I still feel I’m in a python world, but Python would parse such dashed arguments into classic ones (see above). TODO look for some best practices for CLI programs, including Python ones, POSIX etc etc etc.

Nel mezzo del deserto posso dire tutto quello che voglio.