Python Decorators and How to Use Them
Decorators are a powerful feature in Python that allow you to modify or enhance the behavior of functions or methods without changing their actual code. They are widely used in frameworks like Flask and Django for tasks such as authentication, logging, caching, and input validation.
What is a Decorator?
At its core, a decorator is a function that takes another function as an argument, adds some functionality, and returns a new function. In Python, functions are first-class objects, meaning you can pass them around just like variables. Decorators take advantage of this flexibility.
Creating a Simple Decorator
Let’s start with a basic example:
def my_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Here, @my_decorator is syntactic sugar for:
say_hello = my_decorator(say_hello)
When you call say_hello(), it actually runs wrapper(), which includes extra behavior before and after the original function.
Decorators with Arguments
If the decorated function accepts arguments, the wrapper needs to handle them:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Function is about to run")
result = func(*args, **kwargs)
print("Function has run")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
The *args and **kwargs allow the wrapper to accept any number of positional and keyword arguments.
Using functools.wraps
When you decorate a function, its metadata (like __name__ and __doc__) can get hidden. Use functools.wraps to preserve it:
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
Common Use Cases
Logging: Automatically log calls to certain functions.
Authentication: Check user permissions before executing sensitive functions.
Timing: Measure how long functions take to run.
Conclusion
Decorators offer a clean, reusable way to extend function behavior without modifying the original code. Mastering them helps you write more modular, readable, and maintainable Python code.
Learn Fullstack Python Training Course
Read More:
Introduction to Python Modules and Packages
Building a CLI App with Python
Creating a Simple Web App with Flask
Django vs Flask: Which One Should You Learn?
Visit Quality Thought Training Institute
Comments
Post a Comment