Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created July 2, 2012 14:50
Show Gist options
  • Save theY4Kman/3033623 to your computer and use it in GitHub Desktop.
Save theY4Kman/3033623 to your computer and use it in GitHub Desktop.
`passedargs` decorator allows the differentiation between a kwarg being passed a default value and no value being provided for a kwarg.
def passedargs(func):
"""
This (unused) decorator adds a `passed` attribute to `func`, a dict whose
keys are the parameter names of `func` and whose values are True if that
particular argument was passed, and False if not. This is useful if you
don't want to use a sentinel value to detect the lack of argument passing.
This is bad, though, because it's harder to get rid of an argument than it
is to change one.
For whatever reason, I got it in my head I wanted to create an Object.get
method, much like dict's, but instead of returning None when default isn't
passed, an Exception would be raised.
>>> @passedargs
... def f(test, default=None):
... print f.passed
...
>>> f('test')
{'test': True, 'default': False}
>>> f('test', None)
{'test': True, 'default': True}
"""
spec = inspect.getargspec(func)
def inner(*args, **kwargs):
inner.passed = {}
i = 0
for i in xrange(len(args)):
inner.passed[spec.args[i]] = True
for i in xrange(i+1, func.func_code.co_argcount):
inner.passed[spec.args[i]] = spec.args[i] in kwargs
return func(*args, **kwargs)
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment