Decorator with parameters in Python

2

I need to implement a decorator with classes or functions that receive parameters, like the following example

@MyDec(flag='foo de fa fa')
def bar(a,b,c):
    print('En bar(...) : ',a,b,c)
    
asked by In DeepLab 11.08.2018 в 21:53
source

1 answer

5
class MyDec(object):
    def __init__(self, flag):
        self.flag = flag

    def __call__(self, original_func):
        decorator_self = self
        def wrappee(*args, **kwargs):
            print('en decorador antes de wrapee ', decorator_self.flag)
            original_func(*args,**kwargs)
            print('en decorador despues de wrapee', decorator_self.flag)
        return wrappee

@MyDec(flag='foo de fa fa')
def bar(a,b,c):
    print('En bar(...) : ',a,b,c)

if __name__ == "__main__":
    bar(1, "Hola", True)

#Out:
# en decorador antes de wrapee  foo de fa fa
# en bar 1 Hola True
# en decorador despues de wrapee foo de fa fa

Initially we create a class MyDec that is going to be the decorator, and in the constructor it receives all the arguments that are necessary in this case we add the statement flag . In the method __call__(self) that is the one that is executed when we add the decorator @MyDec(flag='foo de fa fa') in the function. Within the arguments of __call__ this original_func which is the function to which the decorator is placed. And within wrappee() we receive the arguments of the function and later we execute the function original_func(*args,**kwargs) and we pass the arguments and the KeyWordsArguments

    
answered by 11.08.2018 / 22:03
source