Python

Python Decorator

Python decorator is callable that take in a function and modify the behaviour of the function without explicitly modify the function code.

Let us the simple example below.

if i have a simple function my_func that return “hello” as shown below

def my_func():
    return "hello"

I would like to modify the output of the function to uppercase “HELLO”. The easiest method is to do

my_func().upper()

However, we can also use decorator method to do this as follows:

def my_decorator(func):
    a = func()
    return a.upper()

@my_decorator
def my_func():
    return 'hello'

my_func
Output:
HELLO

Thus, we are able to modify the output the my_func without modifying the my_func code. The above decorator code has the same effect as follows. So @my_decorator is equivalent to my_func = my_decorator(my_func).

def my_decorator(func):
    a = func()
    return a.upper()

def my_func():
    return 'hello

my_func = my_decorator(my_func)
print(my_func)
Output:
HELLO

References:

Relevant Courses

May 23, 2021