
Decorators in Python are one of the most powerful features that allow developers to modify or extend the behavior of functions without changing their original source code. They improve code reusability, readability, and maintainability. In this guide, you’ll learn how decorators work, their syntax, practical examples, advantages, common use cases, and best practices.
1. Understanding Decorators
A decorator is a function that takes another function as an argument, adds some functionality to it, and returns the modified function. Decorators are often used to add “wrapping” functionality to existing functions in a concise way.
Basic Decorator Example:
python
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed this before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
print("Display function ran")
display()
Output:
arduino
Wrapper executed this before display
Display function ran
2. Creating and Using Decorators
Step-by-Step Example:
- Define the decorator function.
- Define the wrapper function inside the decorator.
- Return the wrapper function.
- Use the @ symbol to apply the decorator to the target function.
Example:
python
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()
Output:
vbnet
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
3. Decorators with Arguments
To create decorators that can accept arguments, you need to define a decorator function that returns another decorator function.
Example:
python
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times=3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Output:
Hello, Alice!
Hello, Alice!
Hello, Alice!
4. Using functools.wraps
When writing decorators, it’s a good practice to use functools.wraps to preserve the original function’s metadata, such as its name, docstring, and module.
Example:
python
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Calling function...")
result = func(*args, **kwargs)
print("Function called")
return result
return wrapper
@my_decorator
def say_hello():
"""A simple greeting function."""
print("Hello!")
print(say_hello.__name__) # Output: say_hello
print(say_hello.__doc__) # Output: A simple greeting function.
5. Decorators with Return Values
Decorators can also work with functions that return values.
Example:
python
def add_greeting(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"Hello, {func(*args, **kwargs)}!"
return wrapper
@add_greeting
def get_name(name):
return name
print(get_name("Alice")) # Output: Hello, Alice!
6. Class-Based Decorators
You can also create decorators using classes by defining a __call__ method.
Example:
python
class DecoratorClass:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Class-based decorator is called")
return self.func(*args, **kwargs)
@DecoratorClass
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Bob")
Output:
vbnet
Class-based decorator is called
Hello, Bob!
7. Common Use Cases for Decorators
- Logging: Adding logging functionality to a function.
- Access Control: Checking if a user has the right permissions before executing a function.
- Caching: Storing results of expensive function calls and reusing them when the same inputs occur again.
- Validation: Validating input data before processing it.
Logging Example:
python
def log_function_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} called with arguments {args} and keyword arguments {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_function_call
def add(a, b):
return a + b
print(add(5, 3)) # Output: Function add called with arguments (5, 3) and keyword arguments {}
# Output: 8
Conclusion
Decorators in Python provide a clean and efficient way to extend the functionality of functions without modifying their source code. Whether you are implementing logging, authentication, caching, or performance monitoring, decorators help you write reusable and maintainable code. By mastering decorators, you can build more modular and scalable Python applications while following modern software development practices.
Check out our Trending Courses Demo Playlist
| Data Analytics with Power Bi and Fabric |
| Could Data Engineer |
| Data Analytics With Power Bi Fabic |
| AWS Data Engineering with Snowflake |
| Azure Data Engineering |
| Azure & Fabric for Power bi |
| Full Stack Power Bi |
Kick Start Your Career With Our Data Job
Social Media channels
► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268


Most Commented