Junior — Middle
Can you explain what the decorator pattern is in Python and how it is used?
sobes.tech AI
Answer from AI
The decorator pattern in Python is a way to dynamically extend the functionality of functions or methods without changing their original code. A decorator is a function that takes another function and returns a new function with additional behavior.
Here's an 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()
Here, @timer is syntactic sugar for some_function = timer(some_function). Decorators are widely used for logging, access control, caching, and other aspects, separating additional logic from the main function.