Manually calls a decorator that takes arguments

I have a f1 function:

def f1(): return True 

I also have a decorator that accepts arguments that can be used as follows:

 @validate_arguments(arg1, arg2) 

I try to call f1 manually without @ (for testing and reuse), but this does not work.

So something like:

 validate_arguments(f1, arg1, arg2) 

The reason this doesn't work is because validate_arguments is a function that takes arguments as parameters and contains a closure that is the actual decorator.

Is there no way to do what I want? To manually call a decorator on a function without @ , for a decorator that takes arguments?

+7
python decorator
source share
1 answer

You need something like:

 def f1(): return True f1 = validate_arguments(arg1, arg2)(f1) 

Here validate_arguments(arg1, arg2) returns the actual decorator, to this decorator we pass the object to the function f1 , which, in turn, returns the new changed function.

Demo:

 def validate_arguments(arg1, arg2): def decorator(func): def wrapped(): print arg1, arg2 return func() return wrapped return decorator def f1(): return True f1 = validate_arguments(1, 2)(f1) print f1() #1 2 #True 
+11
source share

All Articles