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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With