Created
July 6, 2023 08:56
-
-
Save bofm/ff82fa849fbedee73d780ba2087dfc79 to your computer and use it in GitHub Desktop.
Automatically parse args and call a function based on it's 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 inspect | |
from argparse import ArgumentParser | |
def argparse_call(fn): | |
sig = inspect.signature(fn) | |
p = ArgumentParser() | |
for param in sig.parameters.values(): | |
kwargs = { | |
'type': param.annotation, | |
'default': param.default, | |
'required': param.default == inspect.Parameter.empty, | |
} | |
if kwargs['type'] == bool and param.default is False: | |
kwargs['action'] = 'store_true' | |
del kwargs['type'] | |
p.add_argument(f'--{param.name}', **kwargs) | |
args = p.parse_args() | |
return fn(**vars(args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment