Sobes.tech
Junior — Middle

Do you apply the decorator pattern in your projects and how does it help organize code?

sobes.tech AI

Answer from AI

Yes, the decorator pattern is often used to extend the functionality of objects without modifying their original code. In Python, this can be conveniently implemented using classes or wrapper functions.

A decorator helps organize code by separating core logic from additional features, which increases flexibility and reusability.

An example of using a decorator for logging function calls:

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__} with arguments {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper

@log_decorator
def add(a, b):
    return a + b

add(2, 3)

This approach allows adding new features (logging, validation, caching) without changing the original function code.