Skip to content

Instantly share code, notes, and snippets.

@bofm
Created July 6, 2023 08:56
Show Gist options
  • Save bofm/ff82fa849fbedee73d780ba2087dfc79 to your computer and use it in GitHub Desktop.
Save bofm/ff82fa849fbedee73d780ba2087dfc79 to your computer and use it in GitHub Desktop.
Automatically parse args and call a function based on it's signature.
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