Exploring Python Decorators: How They Work and When to Use Them

What is a Decorator in Python?
A decorator is a higher-order function in Python that allows us to modify the behavior of another function or method without changing its code. Decorators are widely used for logging, authentication, memoization (caching), and more.
How Do Decorators Work?
A decorator in Python is simply a function that takes another function as an argument, modifies its behavior, and returns a new function.
Basic Syntax of a Decorator
pythondef 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:
pgsqlSomething is happening before the function is called.
Hello!
Something is happening after the function is called.The @my_decorator syntax is equivalent to say_hello = my_decorator(say_hello).
When to Use Decorators?
1. Logging Function Calls
pythondef log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__} with arguments {args} {kwargs}")
return func(*args, **kwargs)
return wrapper@log_decorator
def add(a, b):
return a + b
print(add(3, 4))
Use case: Debugging and monitoring function calls.
2. Enforcing Authentication
pythondef require_auth(func):
def wrapper(user):
if user != "admin":
print("Access Denied!")
return
return func(user)
return wrapper@require_auth
def secure_function(user):
print(f"Welcome {user}, you have access.")
secure_function("guest") # Access Denied
secure_function("admin") # Welcome adminUse case: Role-based access control.
3. Timing Function Execution
pythonimport timedef timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(2)
print("Function executed")
slow_function()
Use case: Performance measurement and optimization.
4. Caching (Memoization)
pythonfrom functools import lru_cache@lru_cache(maxsize=5)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # Cached results speed up recursion
Use case: Speeding up recursive computations.
Conclusion
Python decorators are powerful tools that allow you to extend the behavior of functions in a clean and reusable way.
They are commonly used for logging, access control, performance measurement, and caching. Mastering decorators can significantly improve the efficiency and readability of your Python programs.
WEBSITE: https://www.ficusoft.in/python-training-in-chennai/
Comments
Post a Comment