Decorator In Python

Decorator In Python

·

2 min read

A decorator in Python is a design pattern that allows behavior to be added to objects dynamically. It's a function that takes another function as an argument and extends its functionality without modifying it. Decorators are widely used in Python for various purposes such as logging, authentication, caching, and more.

In essence, a decorator wraps another function, allowing you to execute code before and/or after the wrapped function runs, or even completely replace the original function with a new one. This enables you to add reusable functionalities to functions or methods without modifying their core logic.

Example 1:-

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()  # Call the original function
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Example 2:-

def smart_divide(func):
    def inner(a, b):
        print("Dividing", a, "and", b)
        if b == 0:
            print("Cannot divide")
            return

        return func(a, b)
    return inner

@smart_divide
def divide(a, b):
    print(a/b)

divide(4,2)

divide(5,0)

In conclusion, decorators in Python provide a powerful mechanism for extending and modifying the behavior of functions or methods without altering their original code. They allow you to add reusable functionalities such as logging, authentication, caching, performance optimization, and more in a clear, concise, and modular way.

Key points about decorators:

  1. Function Wrapping: Decorators wrap functions or methods with additional functionality, enabling you to execute code before and/or after the wrapped function runs, or even replace the original function with a new one.

  2. Syntax: Decorators are implemented using the @decorator_name syntax, which is a convenient way to apply a decorator to a function or method.

  3. Flexibility: Decorators can take arguments and be chained together to create complex behavior. They can also be applied to both standalone functions and methods within classes.

  4. Maintaining Function Metadata: The functools.wraps decorator helps preserve metadata such as docstrings and function names when using decorators.

  5. Common Use Cases: Decorators are widely used in various programming scenarios, including web development, asynchronous programming, testing, and performance optimization.

Overall, decorators are an essential feature of Python that promotes code reusability, modularity, and readability, making it easier to develop and maintain Python applications.

Did you find this article valuable?

Support Deven by becoming a sponsor. Any amount is appreciated!