You are currently viewing What are Decorators in Python?
Python | Decorators

What are Decorators in Python?

Decorators are functions that modify the behavior of another function. In other words, they take one function as input and return another function as output that has some modified behavior. Decorators are a way to implement aspect-oriented programming in Python.

Decorators are a powerful feature of Python that allow for adding functionality to a function without modifying the function’s code. They are used to wrap a function in a wrapper function and modify the behavior of the original function without changing its code. The decorator function takes a function as an argument and returns a new function that wraps the original function.

The syntax of a decorator is as follows:

@decorator_function
def my_function():
    # function body

Here, decorator_function is the function that is used as a decorator. The @decorator_function is a shorthand way of writing:

def my_function():
    # function body

my_function = decorator_function(my_function)

The decorator_function takes the my_function as an argument, modifies its behavior, and returns a new function. The my_function variable is then reassigned to the new function returned by the decorator_function.

There are several built-in decorators in Python, such as @staticmethod, @classmethod, and @property, among others. We can also define our own custom decorators by defining a function that takes a function as an argument

and returns a new function that modifies the behavior of the original function.

Here is an example of a custom decorator that measures the time taken by a function to execute:

import time

def measure_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time} seconds to execute.")
        return result
    return wrapper

@measure_time
def my_function():
    # function body

my_function()

In this example, the measure_time the function is a decorator that takes a function as an argument and returns a new function that measures the time taken by the original function to execute. The wrapper function takes any number of positional and keyword arguments (*args and **kwargs), measures the time taken by the original function to execute, and prints it to the console. Finally, it returns the result of the original function.

The @measure_time decorator is applied to the my_function function, which causes it to be wrapped in the wrapper the function that measures the time taken by my_function to execute. When we call my_function(), it prints the time taken by the function to execute to the console.

Leave a Reply