Decorators are a powerful feature in Python that allow you to modify or extend the behavior of functions or classes without changing their source code. They act as special functions that take another function and return a new one, often used for logging, access control, or caching.
Key Uses of Decorators
- 🛠️ Function Wrapping: Add functionality before or after a function call
- 🔧 Metadata Addition: Attach extra information to functions
- 📦 Class Modification: Alter class behavior dynamically
- 🚀 Code Reusability: Avoid repetitive code patterns
Example: Simple Decorator
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello, world!")
say_hello()
How Decorators Work
- The decorator function
my_decorator
is defined - It takes the target function
say_hello
as an argument - Returns a wrapper function that executes additional code
- The original function is then called within the wrapper
For more advanced use cases, check our Python Advanced Topics Guide.