Created
October 23, 2016 15:09
-
-
Save gab50000/c4c57457799e552b9bd221664f14ee15 to your computer and use it in GitHub Desktop.
Python function annotation for easier argparse handling
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
#!/usr/bin/env python3 | |
from functools import wraps | |
import inspect | |
def argparse_compatible(func): | |
"""Decorator that enables calling a function with its arguments or using an argparse.Namespace object. | |
For example, the function | |
@argparse_compatible | |
def f(a, b, c): | |
return None | |
can be called via | |
f(a, b, c) | |
or via | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-a") | |
parser.add_argument("-b") | |
parser.add_argument("-c") | |
args = parser.parse_args() | |
f(args) | |
""" | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if len(args) == 1 and type(args[0]) == argparse.Namespace: | |
expected_args = inspect.signature(func).parameters.keys() | |
args = {arg: getattr(args[0], arg) for arg in expected_args if hasattr(args[0], arg)} | |
return func(**args) | |
else: | |
return func(*args, **kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment