Sobes.tech
Junior — Middle

What is a custom decorator and how to create one in Python?

sobes.tech AI

Answer from AI

A custom decorator in Python is a function that takes another function as input and returns a new function with extended or modified behavior.

Example of creating a simple decorator that prints a message before and after the function call:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Starting function execution")
        result = func(*args, **kwargs)
        print("Finished function execution")
        return result
    return wrapper

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

say_hello("World")

Here, @my_decorator applies the decorator to the say_hello function, adding extra output.

What is a custom decorator and how to create one in… - sobes.tech