May 18, 2022

Choosing Singular or Plural for Argument Names in Argparse

Naming is hard, right? Today I was extending an argparse based CLI application. I wanted to add an optional argument so that I can pass in environment variables. For this argparse has a special “action”, called append. From the argparse documentation: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='append') >>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2']) Awesome! Now I can access all the provided values as foo. Wait a moment Wait! This does not match....

February 7, 2022

How to Gracefully Rename a Command Line Argument in an Argparse Application

The CI runner I am currently working on can be used as follows: lpcraft run --output Now, what is output? A boolean? In the sense of “do create output”? A path to a directory? Something else? disambiguate --output can be used to specify a directory for the build artifacts. So, let’s rename it to --output-directory - problem solved. Yes, but what about all the users out there… argparse magic to the rescue We all know argparse is magic, and sometimes that even helps....

November 30, 2021

Testing Argparse Applications - the Better Way

When you are creating command line applications in Python, you probably heard of argparse, which is a great library for exactly doing this, and it is even included in Python’s standard library. Imagine you have created the following argparse application: <main.py> import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--name', required=True) args = parser.parse_args() print(f'Hello {args.name}') if __name__ == '__main__': sys.exit(main()) Looks straightforward, works great, but at one point, you certainly want to add tests for it, right?...