Python Decorators
Python Decorators
TRE
In Python, a decorator is a design pattern
that allows you to modify the functionality
CEN
of a function by wrapping it in another
function.
NG
The outer function is called the decorator,
RN I
which takes the original function as an
argument and returns a modified version of
L EA
it.
CH
add_five = outer(5)
TRE
result = add_five(6)
CEN
print(result) # prints 11
NG
# Output: 11
RN I
Here, we have created the inner() function
L EA
inside the outer() function.
CH
result = calculate(add, 4, 6)
print(result) # prints 10
TRE
CEN
In the above example, the calculate() function
NG
takes a function as its argument. While
RN I
calling calculate(), we are passing the add()
returns 10.
ALW
greet = greeting("MANPREET")
TRE
print(greet()) # prints "Hello, MANPREET!"
CEN
# Output: Hello, MANPREET!
NG
RN I
In the above example, the return hello
L EA
statement returns the inner hello() function.
variable.
IN F
Python Decorators
As mentioned earlier, A Python decorator is
TRE
special __call__() method is termed callable.
CEN
So, in the most basic sense, a decorator is
NG
a callable that returns a callable.
RN I
Basically, a decorator takes in a function,
L EA
adds some functionality and returns it.
CH
O TE
def make_pretty(func):
def inner():
IN F
func()
return inner
ALW
def ordinary():
print("I am ordinary")
# Output: I am ordinary
TRE
● ordinary()
CEN
● make_pretty()
NG
inner(), and returns the inner function.
RN I
L EA
We are calling the ordinary() function
CH
function.
A YS
def make_pretty(func):
ALW
TRE
# define ordinary function
CEN
def ordinary():
print("I am ordinary")
NG
RN I
# decorate the ordinary function
decorated_func = make_pretty(ordinary)
L EA
# call the decorated function
CH
decorated_func()
O TE
IN F
Output:
I got decorated
A YS
I am ordinary
ALW
TRE
inner function, and it is now assigned to
CEN
the decorated_func variable.
NG
decorated_func()
RN I
Here, we are actually calling the inner()
L EA
function, where we are printing
CH
O TE
def make_pretty(func):
def inner():
TRE
func()
CEN
return inner
NG
RN I
L EA
@make_pretty
CH
def ordinary():
O TE
print("I am ordinary")
IN F
A YS
ALW
ordinary()
Output:
I got decorated
I am ordinary
Here, the ordinary() function is decorated
TRE
CEN
NG
RN I
L EA
CH
O TE
IN F
A YS
ALW