Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of a function or class without permanently modifying the callable itself.
Function decorators take function references as arguments and wrap them in a wrapper before returning the function with the wrapper as a new function.
First Class Objects
Functions are first-class objects in Python, which means that they can be used or passed as arguments.
Example :
def uppertext(text):
return text.upper()
def gettext(func):
res = func("codeinpocket")
print(res)
gettext(uppertext)
Output : CODEINPOCKET
In above example the gettext function takes another function as a parameter (uppertext in this case). The function passed as an argument is then called inside the function gettext .
Decorators
A decorator takes in a function, adds some functionality and returns it. we can call decorators function using @
sign.
Syntax
@decorator_func_name
Example : Division two numbers
def decor(func):
print("inside decor()")
def indecor(x,y):
print("before execution")
if x > y:
res = func(x,y)
print("after execution")
return res
else:
print("invalid input")
return indecor
@decor
def div(a,b):
print("inside div()")
print("result is : ",a/b)
div(4,2)
Output : inside decor() before execution inside div() result is : 2.0 after execution
In above example decor function takes div function as parameter and return result only if the condition was true otherwise will return error.
That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.
—
If you like this article, you can buy me a coffee. Thanks!