Junior — Middle
В каких случаях уместно использовать декоратор в коде?
sobes.tech AI
Answer from AI
A decorator in Python is appropriately used when you need to add additional behavior to a function or method without changing their original code. It allows implementing reusable wrappers for logging, access control, measuring execution time, and other aspects.
Examples of decorator use cases:
- Logging function calls.
- Caching results.
- Checking user permissions before executing a function.
- Measuring execution time.
A simple example of a logging decorator:
def log_calls(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_calls
def add(a, b):
return a + b
add(2, 3)
Using a decorator helps separate additional logic from the main code, making it cleaner and easier to maintain.