Implementing dynamic, use-case dependent argparse in Python

Cpak
2 min readAug 28, 2020

Problem Statement

Python’s argparse works great for specifying dynamic arguments when a Python program is launched/run. However, as your organization’s data analytics capabilities grows, it becomes useful to specify arguments for only specific use-cases. For instance, for some analytics, you may want to specify the department name (but not the product type), and for other analytics, you may want to specify the product type (but not the department name). As the number of use-cases and analytics grows, the number of arguments you will need to keep track of will grow accordingly. Over time, you may find it difficult to map the relationship between use-case-dependent arguments and their use-cases.

Let’s assume that we have two analytic use-cases ( [A, B]), which share some generic arguments (x). However, use-case A requires the additional argument ( y); whereas, use-case B requires the additional argument ( z ).

Solution

The following solution, inspired by a StackOverflow post, allows you to organize and parse arguments by use-cases A and B.

import argparseclass UserNameSpace(object):
pass
def start_argparser():
parser = argparse.ArgumentParser(
description='Use Case Dependent ArgParse',
conflict_handler='resolve'
)
return parser
def get_shared_cli_args(
parser
)…

--

--