Skip to content

Instantly share code, notes, and snippets.

@alvinwan
Created February 26, 2024 07:28
Show Gist options
  • Save alvinwan/2894c903467225d796e84cc7e962f358 to your computer and use it in GitHub Desktop.
Save alvinwan/2894c903467225d796e84cc7e962f358 to your computer and use it in GitHub Desktop.
Extract argparse information
import argparse
import json
def get_argparse_spec_as_dict(parser):
"""
Gets the argparse spec as a dictionary.
This makes transformations on the argument parser a little
easier.
"""
arguments = []
for action in parser._actions:
argument = {}
for key, value in vars(action).items():
if key == 'option_strings':
argument[key] = list(map(str, value))
continue
if isinstance(value, (str, int)) or value is None:
# These are all normal, jsonify-able values.
argument[key] = value
continue
if key == 'container':
# This is an ArgumentGroup object that we don't
# really need to 'export'
continue
# NOTE: This clause really only applies to the type. You
# could optionally keep this as a function, to use later.
# This is stringified to support JSONifying.
argument[key] = str(value)
arguments.append(argument)
return {'arguments': arguments}
# Normal parser definition. Note that we don't have to call parse_args
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=int, help='an integer argument')
parser.add_argument('--bar', type=str, help='a string argument')
# Get the argparse spec as JSON and print it.
spec = get_argparse_spec_as_dict(parser)
print(json.dumps(spec, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment