Decorators are not just a “cool trick” in Python — they are widely used in real-world projects. Let’s look at some common and powerful use cases.
1) Logging Function Calls
Decorators can be used to keep track of function execution. This is useful in debugging and monitoring.
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} was called with arguments {args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_function_call
def add(a, b):
return a + b
print(add(5, 3))
Output:
Function add was called with arguments (5, 3) {}
8
2) Measuring Execution Time
You can measure how long a function takes to run by wrapping it with a decorator.
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.4f} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(2)
print("Finished!")
slow_function()
3) Access Control (Authentication)
Decorators can be used to restrict access to certain functions. For example, in web frameworks, decorators are often used for authentication.
def require_admin(func):
def wrapper(user, *args, **kwargs):
if user != "admin":
print("Access denied!")
return None
return func(user, *args, **kwargs)
return wrapper
@require_admin
def delete_user(user, username):
print(f"User {username} deleted by {user}")
delete_user("guest", "alice") # Access denied
delete_user("admin", "bob") # Works
4) Caching Results
Some functions return the same result if called with the same arguments. Instead of recalculating, we can store (cache) the results using a decorator.
def cache(func):
stored = {}
def wrapper(*args):
if args in stored:
print("Fetching from cache...")
return stored[args]
result = func(*args)
stored[args] = result
return result
return wrapper
@cache
def multiply(a, b):
print("Calculating...")
return a * b
print(multiply(2, 5))
print(multiply(2, 5)) # Uses cached value
5) Summary
- Logging → Track function calls
- Timing → Measure execution speed
- Authentication → Control who can access functions
- Caching → Avoid recalculating repeated results
No comments:
Post a Comment