Sobes.tech
Junior — Middle

How to create a custom decorator in a programming language?

sobes.tech AI

Answer from AI

In Python, a decorator is a function that takes another function and returns a new function with extended behavior. To create your own decorator, you need to define a function that takes a function as an argument, inside which you define a nested function (wrapper) that calls the original function and adds the desired functionality, and then return this wrapper.

Here's an example of a simple decorator that prints a message before and after calling a function:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs)
        print("After calling the function")
        return result
    return wrapper

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

say_hello("World")

Output:

Before calling the function
Hello, World!
After calling the function

Thus, a decorator allows you to wrap a function with additional behavior without modifying its code.