Created
July 2, 2012 15:00
-
-
Save theY4Kman/3033664 to your computer and use it in GitHub Desktop.
Python default matching decorator and default value retrieval function
This file contains hidden or 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
class matchdefaults(object): | |
""" | |
This decorator swaps out the decorated function's default values to the | |
`match` function. This does not sanity check the number of parameters or | |
their names. | |
""" | |
def __init__(self, match): | |
self.match = match | |
def __call__(self, func): | |
func._func_defaults = copy(func.func_defaults) | |
func.func_defaults = self.match.func_defaults | |
return func | |
def default_arg(func, argname): | |
argnames = inspect.getargspec(func).args | |
defaults = func.func_defaults or () | |
arg_defaults = dict(zip(argnames[len(defaults)-1:], defaults)) | |
return arg_defaults[argname] | |
def get_default_arg(func, argname, default=None): | |
try: | |
return default_arg(func, argname) | |
except KeyError: | |
return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment