Python decorators are a powerful feature that allows you to extend and modify the behavior of functions or methods in a flexible and reusable way.
They enable you to wrap another function and execute code before or after the wrapped function runs, without modifying its core logic.
In this post, we’ll explore what decorators are, how they work, and how you can use them in real-world scenarios.
What Are Python Decorators?
A decorator in Python is a function that takes another function as input and returns a new function that typically extends the behavior of the original function.
Decorators provide a clear and concise way to implement cross-cutting concerns such as logging, access control, or performance measurement, without cluttering the main logic of your code.
How Decorators Work
At its core, a decorator is simply a function that wraps another function. The wrapping function can modify the input, output, or even the internal behavior of the original function.
The decorator is applied using the @decorator_name
syntax, which is placed above the function to be decorated.
Here’s a basic example of a decorator:
def simple_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@simple_decorator
def greet():
print("Hello, World!")
greet()
In this example, the simple_decorator
function wraps the greet
function.
When greet()
is called, it first executes the wrapper
function, which runs code before and after calling the original greet
function.
Real-World Examples
Decorators are commonly used to add functionality like logging, enforcing permissions, or measuring execution time.
- Logging
Logging is a common task in software development, and decorators provide an easy way to implement it.
def log(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"{func.__name__} finished")
return result
return wrapper
@log
def calculate(a, b):
return a + b
calculate(5, 3)
This decorator logs the name of the function being called and when it completes.
2. Access Control
You can use decorators to check permissions before allowing access to a function.
def requires_permission(func):
def wrapper(user, *args, **kwargs):
if user.is_admin:
return func(*args, **kwargs)
else:
raise PermissionError("Permission denied")
return wrapper
@requires_permission
def delete_user(user):
print(f"User {user.name} deleted")
In this example, the requires_permission
decorator checks if the user has the necessary permissions before executing the function.
3. Timing Functions
Measuring how long a function takes to run can be easily done with a decorator.
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time} seconds")
return result
return wrapper
@timer
def complex_calculation():
time.sleep(2)
return "Done"
complex_calculation()
Here, the timer
decorator measures the execution time of the complex_calculation
function.
Advanced Usage of Decorators
Decorators can be stacked or parameterized for more complex behavior.
- Stacking Decorators
Multiple decorators can be applied to a single function. They are applied in the order they are listed, from bottom to top.
@timer
@log
def multiply(a, b):
return a * b
multiply(4, 5)
In this case, the log
decorator is applied first, followed by the timer
decorator.
2. Parameterized Decorators
Sometimes, you may want to pass arguments to a decorator. This is done by defining a decorator that returns another decorator.
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()
The repeat
decorator allows you to specify how many times the function should be executed.
Conclusion
Python decorators are a versatile tool for enhancing your code with additional functionality.
They keep your code clean and modular, allowing you to add behavior to functions or methods without altering their structure.
With a good understanding of decorators, you can write more efficient and maintainable Python code.
Ready to Level Up Your Python Skills?
“EscapeMantra: The Ultimate Python Ebook” is here to guide you through every step of mastering Python. Whether you’re new to coding or looking to sharpen your skills, this ebook is packed with practical examples, hands-on exercises, and real-world projects to make learning both effective and enjoyable.
Here’s what you’ll get:
- Clear Explanations: Understand Python concepts easily with straightforward guidance.
- Engaging Projects: Work on fun projects like a Snake game and an AI Chatbot to apply what you’ve learned.
- Hands-On Practice: Build your skills with exercises designed to boost your confidence.
👉 Grab your copy. Dive in today and start mastering Python at your own pace. Don’t wait — your programming journey starts now!
🚀 Support My Work and Get More Exclusive Content! 🚀
If you found article helpful and want to see more in-depth content, tools, and exclusive resources, consider supporting me on Patreon.
Your support helps me create and share valuable content, improve projects, and build a community of passionate developers.
👉 Become a Patron Today! Join here to access exclusive source codes, early project releases, and more!
Thank you for your support and for being part of this journey!