Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of a Decorator

I have a question regarding the workings of a decorator. I would like to explain my problem using an example

The code I implemented to understand decorators

import sys
import inspect
def entryExit(f):
    def new_f(self,*args, **kwargs):
        print "Entering", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:] 
        f(self,*args)        
        print "Exited", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]        
    return new_f


class A:
    @entryExit
    def move(self,g,h):
        print "hello"        
        print g,h            

    @entryExit    
    def move1(self,m,n):
        print "hello"        
        print m,n
        return m
a=A()
a.move(5,7)
h=a.move1(3,4)
print h

The output of this code is

Entering move A ['g', 'h']
hello
5 7
Exited move A ['g', 'h']
Entering move1 A ['m', 'n']
hello
3 4
Exited move1 A ['m', 'n']
None

The last line of the output displays None. But the actual meaning of the method is changed by using decorators. The return statement in the method move1 was not executed. The actually output I need would be

Entering move A ['g', 'h']
hello
5 7
Exited move A ['g', 'h']
Entering move1 A ['m', 'n']
hello
3 4
Exited move1 A ['m', 'n']
3

So did I make any mistake while creating a decorator or the decorators always ignores the return statement in a function?

like image 289
Kaushik Avatar asked Dec 01 '25 08:12

Kaushik


1 Answers

To let the function return a value, you would have to change the definition of the decorator to be:

def new_f(self,*args, **kwargs):
    print "Entering", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:] 
    ret = f(self,*args)        
    print "Exited", f.__name__,self.__class__.__name__,inspect.getargspec(f).args[1:]    
    return ret    
return new_f

It's not that decorators "always ignore" the return statement, but that you have to handle the return yourself- in the same way that you had to use *args and **kwargs to handle arguments.

like image 128
David Robinson Avatar answered Dec 02 '25 22:12

David Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!