Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this decorator work in python

I had this decorator written by someone else in code and i am not able to get it

def mydecorator(a, b):
        def f1(func):
            def new_func(obj):
                try:
                    f= func(obj) 
                except Exception as e:
                    pass
                else:
                    if f is None:
                        pass
                    else:
                        f = f, a, b

                return f
            return new_func
        return f1

This is applied to function like this

@mydecorator('test1', 'test2')
def getdata():
   pass

My thinking was that decorator takes function name as argument but here

i am not able to get from where did func came and obj came

like image 808
user3214546 Avatar asked Sep 26 '22 13:09

user3214546


People also ask

How does the decorator work?

Essentially, decorators work as wrappers, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it.

What is Type decorator in Python?

A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function "func" or a class "C" is passed to a decorator and the decorator returns a modified function or class.

What is the benefit of using a decorator Python?

Once you master writing decorators, you'll be able to benefit from the simple syntax of using them, which lets you add semantics to the language that are easy to use. It's the next best thing to being able to extend the syntax of Python itself.

What does a decorator return in Python?

Decorators in Python are very powerful which modify the behavior of a function without modifying it permanently. It basically wraps another function and since both functions are callable, it returns a callable. In hindsight, a decorator wraps a function and modifies its behavior.


1 Answers

This -

@mydecorator('test1', 'test2')
def getdata():
   pass

is similar to (without the decofunc name ever being created) -

decofunc = mydecorator('test1', 'test2')
@decofunc
def getdata():
   pass

Since mydecorator() returns f1 , which accepts the function as the argument.

Then it gets the getdata function as argument. and returns the new_func , and the name getdata is replaced with this new_func , hence whenever you call getdata() it calls this new_func function, which internally calls your original getdata() function.

like image 108
Anand S Kumar Avatar answered Oct 03 '22 17:10

Anand S Kumar