Decorators in Python



In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods without directly modifying their code. Decorators allow you to wrap a function with additional functionality. They are denoted by the "@" symbol followed by the decorator function's name.


Here's a basic example of a decorator:


```python

def my_decorator(func):

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper


@my_decorator

def say_hello():

    print("Hello!")


# Using the decorated function

say_hello()

```


In this example:


1. `my_decorator` is a decorator function that takes another function (`func`) as its argument.

2. `wrapper` is an inner function defined inside `my_decorator`. It adds behavior before and after calling the original function.

3. The `@my_decorator` syntax is used to apply the decorator to the `say_hello` function.


When you call `say_hello()`, it is effectively replaced by the `wrapper` function defined in the decorator. This allows you to modify the behavior of `say_hello` without modifying its original code.


You can also pass arguments to decorators. Here's an example:


```python

def repeat(n):

    def decorator(func):

        def wrapper(*args, **kwargs):

            for _ in range(n):

                func(*args, **kwargs)

        return wrapper

    return decorator


@repeat(3)

def greet(name):

    print(f"Hello, {name}!")


# Using the decorated function

greet("Alice")

```


In this example, the `repeat` decorator takes an argument `n` and repeats the decorated function `n` times. The `@repeat(3)` syntax applies the decorator with `n=3` to the `greet` function.


Decorators are commonly used for tasks such as logging, authorization, caching, and more. Python itself provides several built-in decorators, and you can also create custom decorators to suit your specific needs. Decorators provide a clean and elegant way to extend or modify the behavior of functions in a reusable manner.

Comments