Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created July 2, 2012 15:00
Show Gist options
  • Save theY4Kman/3033664 to your computer and use it in GitHub Desktop.
Save theY4Kman/3033664 to your computer and use it in GitHub Desktop.
Python default matching decorator and default value retrieval function
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