Skip to content

Instantly share code, notes, and snippets.

@AntonOsika
Last active May 14, 2019 11:21
Show Gist options
  • Save AntonOsika/5c124dfa5c84729533d6305b0134df64 to your computer and use it in GitHub Desktop.
Save AntonOsika/5c124dfa5c84729533d6305b0134df64 to your computer and use it in GitHub Desktop.
Simple and powerful technique for defining command line arguments.
import argparse
def parsed_arguments(defaults: dict) -> argparse.Namespace:
"""
Sets all variables defined in default_args() as command line arguments.
(e.g. specify job_dir with: --job-dir [job_dir])
Args:
defaults: dict of default argument names and values. Any `_` will be replaced with `-`.
Returns:
argparse.Namespace
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
for key, val in defaults.items():
# Replace underscore in variable names with hyphen:
key = key.replace('_', '-')
t = type(val)
kwargs = {}
if t == list:
kwargs['nargs'] = '*' # inputs are space separated arguments
if t == bool:
t = int # bool has to be given as 0/1
parser.add_argument(
'--' + key,
default=val,
type=t,
help=t.__name__,
**kwargs
)
return parser.parse_args()
def default_args():
batch_size = 32
job_dir = ''
return locals()
def process_flags(flags):
if flags.job_dir == '':
flags.job_dir = None
def parse():
"""
Sets all variables defined in default_args() as command line arguments.
(e.g. specify job_dir with: --job-dir [job_dir])
"""
all_defaults = default_args()
parsed_arguments(all_defaults)
return parsed_arguments
def main():
flags = parse()
process_flags(flags)
print(flags.job_dir)
# If you need all arguments, e.g. for writing to disk as text:
for k, v in flags.__dict__.items():
print('{}: {}'.format(k, v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment