Doubt with decorators in Python

1

I have a question with the application of decorators.
I understand that a decorator is a function that receives another function as a parameter and "wraps" it. But if this function has to return a value ( return ) it returns it as None . However, with print it works without problems. I do not understand well why func1 works without problems and func2 not:

# EJEMPLO BÁSICO DE DECORADOR 1

def decorador(func):
    def wraper(*args,**kwargs):
        print ("inicio de función")
        func(*args, **kwargs)
        print ("Final de función")
    return wraper

@decorador
def func1(text):
    print (text)

@decorador
def funz2(text):
    return (text)

func1("función 1")
a = funz2("función 2")
print (a)

The result is:

inicio de función
función 1
Final de función
inicio de función
Final de función
None
    
asked by BigfooTsp 24.04.2018 в 22:55
source

1 answer

0

Once you have decorated a function, when you call the function you are really calling the decorator. Therefore if you want to have a returned value, you must have it returned by the decorator. Since what you want to return is what would have returned the wrapped function, capture that result inside the decorator to return it to the end.

Like this:

def decorador(func):
    def wraper(*args,**kwargs):
        print ("inicio de función")
        resultado = func(*args, **kwargs)
        print ("Final de función")
        return resultado
    return wraper

Your decorator was also running smoothly, except that when you reached the end without an explicit% return , an% imp_de% was made.

    
answered by 24.04.2018 в 23:08