Learn Python Programming

Python Decorators

A decorator is a function that accepts a function as an argument and returns a function itself. Decorator takes the result of a function, modifies the result and returns it.

Let us understand with an example:

Example 1:

def function_one(func):
    print("This is function one.")

def function_two():
    print("This is function two.")


This is function one.
This is function two.

Here in the above example, inside function_one, we are passing function_two. So first it will go to check the argument and pick the function_two passed as a parameter in function_one. And it will printer first print() statement. And then it will call the function_two() and print its statment.

def function1():
    def function2():
        print("This is function2.")
        return 1
    return function2

my_func = function1()    

This is function2.

Steps to create a decorator:

  • You should define a decorator function with another function name as an argument. Let suppose a my_decorator() function having a function ‘func’ as an argument.
    def my_decorator(func):
  • You should define a function inner function inside the my_decorator() function. This function actually modifies or decorates the values of the function passed to the decorator function.
def my_decorator(func):
    def inner():
        value = func()
        return value+2
    return inner

def num():
    return 10

#call decorator function and pass function num() as a parameter...
result_decor = my_decorator(num)