Sobes.tech
Senior

What are decorators in Python?

sobes.tech AI

Answer from AI

Decorators in Python are functions or classes that take another function or method and return a new function with extended or modified behavior, without changing the original code of the decorated function.

They are often used for adding logging, permission checks, caching, measuring execution time, and other aspects unrelated to the main logic of the function.

A simple decorator example:

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

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

say_hello("World")

Here, @decorator wraps the say_hello function, adding output messages before and after its call.

What are decorators in Python? — QA / QA Automation - sobes.tech