Skip to content

Instantly share code, notes, and snippets.

@judy2k
Created April 10, 2016 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judy2k/a25c4fbfa1d375a7aab648bf4d77d2bf to your computer and use it in GitHub Desktop.
Save judy2k/a25c4fbfa1d375a7aab648bf4d77d2bf to your computer and use it in GitHub Desktop.
argparse -> function call
# 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