Sobes.tech
Junior — Middle

Tell about your experience with applying and writing decorators in code.

sobes.tech AI

Answer from AI

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

Use cases:

  • Logging function calls.
  • Access rights verification.
  • Caching results.

Example of a simple decorator that outputs the execution time of a function:

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 some_function():
    time.sleep(1)

some_function()

This approach helps add functionality without changing the original code of functions.