Junior — Middle
Explain what the decorator pattern in Python is and how to apply it.
sobes.tech AI
Answer from AI
The decorator pattern in Python is a way to dynamically extend the functionality of a function or method without changing their original code. A decorator is a function that takes another function and returns a new function with additional behavior.
Usage:
- Allows adding logging, permission checks, caching, and other aspects without code duplication.
- Used with the syntax
@decoratorabove the function definition.
Example:
def decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} finished")
return result
return wrapper
@decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
In this example, when calling say_hello, it first outputs a message about the start of the call, then executes the function itself, and afterwards outputs a message about completion.