Sobes.tech
Junior — Middle

Can you give examples of using decorators in Python?

sobes.tech AI

Answer from AI

Decorators in Python are used to modify or extend the behavior of functions or methods without changing their code. Examples of usage:

  1. Logging function calls:
def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

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

say_hello("World")
  1. Access rights verification:
def requires_admin(func):
    def wrapper(user, *args, **kwargs):
        if not user.is_admin:
            raise PermissionError("Access denied")
        return func(user, *args, **kwargs)
    return wrapper

@requires_admin
def delete_user(user, user_id):
    print(f"User {user_id} has been deleted")
  1. Caching results:
from functools import lru_cache

@lru_cache(maxsize=32)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

Decorators allow writing cleaner and more reusable code.