Learn python-decorators-guide in Python with step-by-step examples.
Decorators in Python are a powerful feature that allows you to modify the behavior of functions or classes. A decorator is essentially a function that takes another function as an argument, adds some kind of functionality, and returns another function without modifying the source code of the original function.
Decorators are useful because they promote code reusability and separation of concerns. They allow you to add functionality (like logging, timing, access control, etc.) to existing code in a clean and readable way, without cluttering the primary logic of your functions.
Common use cases for decorators include logging function calls, measuring execution time, enforcing access control, memoization (caching function results), and input validation. They are widely used in frameworks such as Flask and Django for route handling and permissions.
# Simple Python decorator example
def my_decorator(func):
def wrapper():
print('Something is happening before the function is called.')
func()
print('Something is happening after the function is called.')
return wrapper
@my_decorator
def say_hello():
print('Hello!')
say_hello()