Decorators
Status
This note is complete, reviewed, and considered stable.
Decorators in Python are a powerful feature that allows us to modify or enhance the behavior of functions or classes without modifying their actual code. They are often used to wrap another function or method, adding extra functionality in a clean and reusable manner.
A decorator in Python is a callable (usually a function) that takes another function (or class) as its argument and returns a modified or extended version of that function (or class).
Why Use Decorators?
- Code Reusability: Common functionality (e.g., logging, authentication, performance monitoring) can be extracted and reused across multiple functions or classes.
- Separation of Concerns: The original function’s core logic is preserved, while additional features are handled externally.
- Improved Readability: Decorators make it easier to apply functionality without cluttering the main code.
How Do Decorators Work?
A decorator is essentially a higher-order function, meaning it either:
- Takes a function as an argument, or
- Returns a function.
At its core, a decorator works like this:
def decorator(func):
def wrapper():
# Code to execute BEFORE the original function
print("Before the function call.")
# Call the original function
func()
# Code to execute AFTER the original function
print("After the function call.")
return wrapper
If you apply this decorator to a function:
@decorator
def my_function():
print("This is my function.")
my_function()
Output:
Before the function call.
This is my function.
After the function call.