Sobes.tech
Junior — Middle

Experience using the decorator pattern in Python and its application in real projects

sobes.tech AI

Answer from AI

The decorator pattern in Python allows dynamically extending the functionality of objects without modifying their original code. In Python, this is often implemented using decorator functions.

Example: logging function calls.

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"Execution time of {func.__name__}: {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def compute(x):
    return sum(i*i for i in range(x))

compute(100000)

In real projects, decorators are used for caching, access control, logging, and other aspects, allowing the main logic to be separated from auxiliary functions.