top of page

Introduction to Python Decorators

In Python, a decorator is a way to add extra features or behavior to a function or method without changing its original code. It's like wrapping a gift with an additional layer of paper or ribbon to make it more attractive, but in this case, it's about adding extra functionality to a piece of code. In this article, we will provide an introduction to Python decorators. We will cover the basic syntax of decorators, how to create and use them, and some common use cases.


What is Python Decorator?

Python decorators are functions that take another function or method as an argument and extend or modify its behavior without actually changing its source code. Using decorators can help simplify code, make it more readable and maintainable, and enable code reuse. Decorators can be used for a wide range of purposes, such as logging, timing, validation, and authorization, among others.


When you use a decorator, you apply it to the function or method you want to modify by using the decorator syntax. The decorator then returns a new function or method that incorporates the added functionality. When you call the original function or method, the decorator is executed first, followed by the original function or method.


Basic Syntax of Decorators

The syntax for a decorator is as follows:

@decoratordef function():
    # function body

The @decorator syntax is called a decorator syntax. It is equivalent to the following code:

def function():
    # function body
function = decorator(function)

This code defines a new function that wraps the original function with some additional functionality.



Example:

import time

def timer_decorator(func):
    def wrapper():
        start_time = time.time()
        result = func()
        end_time = time.time()
        print("Execution time:", end_time - start_time, "seconds")
        return result
    return wrapper

@timer_decorator
def my_function():
    time.sleep(1)
    return "Hello, World!"

print(my_function())

Output:


Python decorator with Argument

def repeat(num_repeats):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(num_repeats):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(num_repeats=3)
def my_function():
    print("Hello, World!")

my_function()

In this example, the repeat decorator takes a parameter num_repeats and returns another decorator. This second decorator takes a function func as an argument and returns a new function wrapper that wraps the func function. The wrapper function executes the func function multiple times, as specified by the num_repeats parameter.


To apply the repeat decorator to a function, we use the @repeat(num_repeats=3) syntax, which specifies the value of the num_repeats parameter.


In this case, we apply the repeat decorator to the my_function function and set the num_repeats parameter to 3. When we call my_function, it is wrapped by the repeat decorator, which causes it to execute 3 times in a row.


Output:


Chaining Decorator in Python

Multiple decorators can be chained in Python.


To chain decorators in Python, we can apply multiple decorators to a single function by placing them one after the other, with the most inner decorator being applied first.

def star(func):
    def inner(*args, **kwargs):
        print("*" * 15)
        func(*args, **kwargs)
        print("*" * 15)
    return inner


def percent(func):
    def inner(*args, **kwargs):
        print("%" * 15)
        func(*args, **kwargs)
        print("%" * 15)
    return inner


@star
@percent
def printer(msg):
    print(msg)

printer("Hello World!")

Output


Benefits of Python Decorator

Python decorators offer several benefits, including:

  1. Code reusability: Decorators allow you to add common functionality to multiple functions or methods in your codebase without duplicating the code. This makes your code more modular and easier to maintain.

  2. Separation of concerns: By separating the core functionality of a function from its additional behaviors, you can improve the readability and organization of your code.

  3. Dynamic modification of behavior: Decorators provide a way to modify the behavior of functions or methods at runtime, allowing you to adapt your code to changing requirements or conditions.

  4. Improved code performance: Decorators can be used to cache function results or optimize function behavior, which can lead to faster and more efficient code.

  5. Easy to use: Python decorators are easy to use and require only a few lines of code to implement. This makes them accessible even to beginner programmers.

0 comments

Recent Posts

See All
bottom of page