What is a decorator in Python and how to use it?

A decorator in Python is a special type of function that modifies or extends the behavior of another function, usually without having to modify the code of the original function. It's a way to "wrap" or "decorate" a function with additional functionality. You can use decorators to add things like logging, access control, or timing information to a function. To use a decorator in Python, you can define the decorator function and then add the "@" symbol followed by the decorator name before the function that you want to decorate. Here's an example:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

def say_hello(name):
    print(f"Hello, {name}!")


When you run this code, the output will be:

Something is happening before the function is called.
Hello, John!
Something is happening after the function is called.

This is just a simple example to show how decorators work. In practice, decorators can be much more complex and useful.

Related Questions You Might Be Interested