Junior — Middle
How can you create a decorator in Python and how to use it?
sobes.tech AI
Answer from AI
A decorator in Python is a function that takes another function and returns a new function with extended behavior, without modifying the original code.
You can create a decorator like this:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
Using a decorator is convenient with the @ syntax before defining a function:
@decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
The output will be:
Before calling the function
Hello, World!
After calling the function
Thus, decorators allow adding additional logic (such as logging, permission checks, caching) to functions without changing their code.