Middle
What is a decorator in Python and what is it used for?
sobes.tech AI
Answer from AI
A decorator in Python is a function that takes another function and returns a new function with extended or modified behavior, without changing the source code of the decorated function.
Decorators are often used for:
- Logging function calls
- Access control checks
- Caching results
- Measuring execution time
An example of a simple decorator that prints a message before and after calling a function:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
Output:
Before calling the function
Hello, World!
After calling the function
Thus, decorators make it convenient and clean to add additional behavior to functions.