Dremendo Tag Line

Decorators in Python Programming

Function in Python

In this lesson, we will understand what is Decorators in Python Programming and how to create them along with some examples.

What are Decorators in Python Programming?

Decorators are functions that takes another function as an argument and modify its behaviour without directly changing its source code.

video-poster

Decorators Example 1

# this is our decorator function
def decorate_message(func):
    def inner():
        print('***********')
        func()
        print('***********')
    return inner


# This is a simple function that prits Hello World
def message():
    print("Hello World")

msg=decorate_message(message)
msg()

Output

***********
Hello World
***********

In the above program, we have declared a function called message() that will print the text Hello World on the screen. On line number 2, we have declared a decorator function called decorate_message().

The decorate_message function will take another function as an argument, and using a nested function called inner we will decorate the output of the function that is passed as as argument to the decorate_message function.

On line number 14, we are calling the decorate_message function and pass the message function to it. The decorate_message function will return the address of the inner function, which is stored in a variable called msg. On line number 15, we are executing the inner function using the name msg().

Decorators Example 2

# this is our decorator function
def decorate_message(func):
    def inner():
        print('***********')
        func()
        print('***********')
    return inner


@decorate_message
def message():
    print("Hello World")

message()

Output

***********
Hello World
***********

In the above example, we have written @decorate_message just above the message() function. In this way we can call the message() function directly without being needed to pass it to the decorate_message() function manually.

Decorators Example 3

# this is our first decorator function
def decorate_message(func):
    def inner():
        print('***********')
        print(func())
        print('***********')
    return inner


# this is our second decorator function
def decorate_upper(func):
    def inner():
        txt=func();
        return txt.upper()
    return inner


# The message function applies multiple decorators
@decorate_message
@decorate_upper
def message():
    return "Hello World"

message()

Output

***********
HELLO WORLD
***********

The above example shows how to apply multiple decorators to a function. In the above program, on line number 24, when we call the message() function, then @decorate_upper decorator will execute first and after that @decorate_message decorator will execute.