-1

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!

  • 2
    You need to show the code where you try to use `get`, as well as the complete error traceback (not just the last part) – BrenBarn Jun 19 '16 at 20:45

1 Answers1

0

It may because you are trying to wrap a method of a class with the decorator. The requirements for writing decorators which work on methods of a class are a bit different, even worse if you need the one decorator which can work on both normal functions and methods of a class.

You are much better off using a package which helps you to implement the decorator rather than trying to do it yourself, as there are many gotchas if trying to do it yourself.

I would suggest you look at the wrapt package. See:

Is worthwhile also reading:

if you believe hand rolled decorators are always going to work.

As noted above, otherwise provide the code where get() is being called. If this call is being down in some fancy way, that could be causing an issue.

Graham Dumpleton
  • 57,726
  • 6
  • 119
  • 134
  • I don't think being a method is the problem in the questioner's case. It certainly *can* be an issue, but decorators generally work fine as long as they're returning a function (rather than some other kind of callable) and the wrapper function does not modify the positional arguments in a way that breaks `self`. – Blckknght Jun 20 '16 at 00:56