dimanche 3 juillet 2016

Python decorators with *args and **kwargs failing to execute with error message about too many positional arguments

Any article, tutorial, etc. I have read on writing decorators in Python has pointed me to using *args and **kwargs to write decorators which can be applied to any function and / or method (including this great introduction).

However I now have the following code:

def format_result(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        # do something with result
        return result

    return func_wrapper

Which I then use as follows:

class CategoryList(BaseResource):
    '''List or create categories'''

    @format_result
    def get(self):
        '''Create a new category'''
        return {'id': 1, 'name': 'Test Category'}

When using this code in my application, I always receive the following error message:

File "...__init__.py", line 66, in func_wrapper
    result = func(*args, **kwargs)
TypeError: get() takes 1 positional argument but 2 were given

Am I doing something wrong? If relevant, my python -V is "Python 3.5.1".

Thank you very much in advance!

Aucun commentaire:

Enregistrer un commentaire