Master Python Decorators: From Basics to Advanced Use Cases
This article explains Python decorators, covering their definition as higher‑order functions, basic syntax, practical examples such as logging, authorization, caching, and nested decorators, and demonstrates how they enhance code modularity, readability, and reusability without altering original functions.
Introduction to Decorators
Decorators are a design pattern that allows adding functionality to a function without modifying its original code. In Python, a decorator is a higher‑order function that takes a function as an argument and returns a new function.
Basic Syntax
Apply a decorator by prefixing the function definition with @decorator_name.
Example
def decorator(func):
def wrapper(*args, **kwargs):
print("Function is being called")
result = func(*args, **kwargs)
print("Function has been called")
return result
return wrapper
@decorator
def say_hello(name):
print(f"Hello, {name}")
say_hello("Alice")The example shows that decorator wraps say_hello, printing messages before and after the original function runs.
Common Use Cases
Logging Record function calls for debugging and monitoring.
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__} with arguments {args} and {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@log_decorator
def add(a, b):
return a + b
add(3, 5)Authorization Check user permissions before allowing function execution.
def authorize(func):
def wrapper(user, *args, **kwargs):
if user == "admin":
return func(*args, **kwargs)
else:
print("Permission denied")
return wrapper
@authorize
def view_dashboard():
print("Dashboard is being viewed")
view_dashboard("admin")
view_dashboard("guest")Caching Cache function results to improve performance.
def cache(func):
results = {}
def wrapper(*args):
if args in results:
return results[args]
result = func(*args)
results[args] = result
return result
return wrapper
@cache
def fibonacci(n):
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))Nested Decorators
Multiple decorators can be stacked on a single function; they are applied from the innermost to the outermost.
Example
def decorator1(func):
def wrapper(*args, **kwargs):
print("Decorator 1 before")
result = func(*args, **kwargs)
print("Decorator 1 after")
return result
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("Decorator 2 before")
result = func(*args, **kwargs)
print("Decorator 2 after")
return result
return wrapper
@decorator1
@decorator2
def greet(name):
print(f"Hello, {name}")
greet("Bob")In this case decorator2 runs first, then decorator1.
Conclusion
Python decorators provide a powerful way to simplify tasks such as logging, permission control, and performance optimization, making code more readable, modular, and reusable. Mastering decorators can significantly boost development efficiency and code quality.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
