Decorators in Python are a powerful tool that allows you to modify or enhance functions without changing their source code. They are commonly used for tasks like logging, access control, or caching.
Key Concepts
What is a decorator?
A decorator is a function that wraps another function to add functionality. 🛠️How do they work?
Decorators use the@
symbol and take the target function as an argument.@decorator def function(): pass
Common use cases
- Adding logging 📝
- Enforcing access control 🔒
- Caching results 🧾
- Timing function execution ⏱️
Example
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Further Reading
For more advanced topics, check out our tutorial on Python Functions. 📚