Last active
June 30, 2019 15:51
-
-
Save devforfu/5f32e9708ba25192d8dd3856b5298525 to your computer and use it in GitHub Desktop.
Construct CLI from a signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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