Sobes.tech
Junior — Middle

Have you created your own implementation of a decorator in your projects?

sobes.tech AI

Answer from AI

Yes, creating custom decorators in Python is a common practice for adding additional behavior to functions or methods without modifying their code.

Here's an example of a simple decorator that outputs the execution time of a function:

import time

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

@timer_decorator
def example_function(n):
    total = 0
    for i in range(n):
        total += i
    return total

example_function(1000000)

Such a decorator can be used for logging, access control, caching, and other purposes.