Skip to content

Instantly share code, notes, and snippets.

@devforfu
Last active June 30, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devforfu/5f32e9708ba25192d8dd3856b5298525 to your computer and use it in GitHub Desktop.
Save devforfu/5f32e9708ba25192d8dd3856b5298525 to your computer and use it in GitHub Desktop.
Construct CLI from a signature
import argparse
import signature
def make_cli(func: callable):
parser = argparse.ArgumentParser()
sig = inspect.signature(func)
empty = inspect._empty
for param in sig.parameters.values():
annot = param.annotation
options = {}
if annot is empty:
ptype = str
elif isinstance(annot, tuple):
ptype, help_msg = annot
if help_msg is not empty:
options['help'] = help_msg
else:
ptype = annot
options['type'] = ptype
if param.default is empty:
options['required'] = True
else:
options['default'] = param.default
if annot is empty:
options['type'] = type(options['default'])
name = param.name.replace('_', '-')
parser.add_argument(f'--{name}', **options)
func(**vars(parser.parse_args()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment