This works now for those new to this question:
class ensureparams(object):
"""
Used as a decorator with an iterable passed in, this will look for each item
in the iterable given as a key in the params argument of the function being
decorated. It was built for a series of PayPal methods that require
different params, and AOP was the best way to handle it while staying DRY.
>>> @ensureparams(['name', 'pass', 'code'])
... def complex_function(params):
... print(params['name'])
... print(params['pass'])
... print(params['code'])
>>>
>>> params = {
... 'name': 'John Doe',
... 'pass': 'OpenSesame',
... #'code': '1134',
... }
>>>
>>> complex_function(params=params)
Traceback (most recent call last):
...
ValueError: Missing from "params" dictionary in "complex_function": code
"""
def __init__(self, required):
self.required = set(required)
def __call__(self, func):
def wrapper(*args, **kwargs):
if not kwargs.get('params', None):
raise KeyError('"params" kwarg required for {0}'.format(func.__name__))
missing = self.required.difference(kwargs['params'])
if missing:
raise ValueError('Missing from "params" dictionary in "{0}": {1}'.format(func.__name__, ', '.join(sorted(missing))))
return func(*args, **kwargs)
return wrapper
if __name__ == "__main__":
import doctest
doctest.testmod()