Created
April 10, 2016 10:45
-
-
Save judy2k/a25c4fbfa1d375a7aab648bf4d77d2bf to your computer and use it in GitHub Desktop.
argparse -> function call
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
# Please note this function is a sketch and there will be (plenty of) edge cases | |
# where it won't do the right thing. | |
def whitelist_dict(d, whitelist): | |
""" | |
Neat function to extract arguments from a dict, d, that are acceptable for | |
calling a target function. | |
`whitelist` can be either a set of acceptable parameter names, or a callable, | |
which will have its parameters inspected. | |
Use it like this: | |
>>> options = argument_parser.parse_args() | |
>>> run(**whitelist_dict(vars(options), run)) | |
""" | |
if callable(whitelist): | |
sig = signature(whitelist) | |
if any(param.kind == Parameter.VAR_KEYWORD for param in sig.parameters.values()): | |
whitelist = None | |
else: | |
whitelist = [ | |
k for k, v in sig.parameters.items() if v.kind in ( | |
Parameter.POSITIONAL_OR_KEYWORD, | |
Parameter.KEYWORD_ONLY, | |
) | |
] | |
return { | |
k: v for k, v in d.items() if whitelist is None or k in whitelist | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment