KingFish
KingFish

Reputation: 9153

Decorator Which Returns a function and Accepts a Parameter

I'm not the best with decorators and I'm trying to build one for a task (obviously). Basically I have my function which I wish to decorate (it's a Django app but it shouldn't matter)

def foo(request, param):
    # do something w/ param

Now I need to build a decorator to take in a parameter:

@mydecorator('VALUE')
def foo(request, param)
    pass

So basically I need my decorator to take in the value foo, do some work with request, then return

Here is what I have so far but it's not working :(

def mydecorator(val):
    @wraps(function)
    def decorator(request, *args, **kwargs):
        # do something with request with respect to val
        return function(request, *args, **kwargs)
    return decorator

Need help, thanks

Upvotes: 1

Views: 925

Answers (1)

Anthon
Anthon

Reputation: 76607

Apart from the second example definition for foo missing a ':' at the end, the main problem is that mydecorator should return a decorator as it is a function call.

If mydecorator would not take an argument you would write:

@mydecorator
    def foo(request, param)
        pass

and not

@mydecorator()
    def foo(request, param)
        pass

given that knowledge you should start with:

from functools import wraps

def mydecorator(val):
    def myrealdecorator(function):
        @wraps(function)
        def decorator(request, *args, **kwargs):
            # do something with request with respect to val
            print 'I know about', val
            return function(request, *args, **kwargs)
        return decorator
    return myrealdecorator

@mydecorator('VALUE')
def foo(request, param):
    print 'inside foo'

foo('arg1', 'arg2')

Upvotes: 2

Related Questions