Concept Explanation
Imagine you have a phone. It does its basic job—calling people. Now, imagine you put a "protective case" on that phone. The phone still makes calls, but now it also has extra protection, maybe a kickstand, and a cool design.
In Python, a Decorator is that protective case. It is a special function that you "wrap" around another function to give it extra behavior without changing the original code. Decorators are widely used in professional Python development for things like logging, security checks, and timing how long a function takes to run.
Syntax or Core Structure
The "Manual" Way vs. The "@" Way
Decorators are higher-order functions (functions that take other functions as input).
def my_decorator(func):
def wrapper():
print("--- Start of Wrapper ---")
func()
print("--- End of Wrapper ---")
return wrapper
# The Manual Way
def say_hello():
print("Hello!")
decorated_hello = my_decorator(say_hello)
decorated_hello()
# The Modern "@" Way (Syntax Sugar)
@my_decorator
def say_hi():
print("Hi!")
say_hi()
Code Example #1 (Basic)
A decorator that converts a function's output to uppercase.
def make_uppercase(func):
def wrapper():
original_result = func()
return original_result.upper()
return wrapper
@make_uppercase
def get_greeting():
return "welcome to the decorators lesson"
print(get_greeting()) # WELCOME TO THE DECORATORS LESSON
Code Example #2 (Intermediate)
Handling arguments in decorated functions using *args and **kwargs. This is how "professional" decorators are written so they can wrap ANY function.
def log_execution(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
result = func(*args, **kwargs)
print(f"Finished: {func.__name__}")
return result
return wrapper
@log_execution
def add(a, b):
return a + b
print(add(10, 20))
Real World Example
Imagine you are building a web application and you want to ensure a user is "Logged In" before they can see certain pages.
# 🔐 Security Decorator
def require_login(func):
def wrapper(user_is_logged_in):
if not user_is_logged_in:
print("Redirecting to login page...")
return
return func(user_is_logged_in)
return wrapper
@require_login
def show_dashboard(user_status):
print("Welcome to your secret dashboard!")
show_dashboard(False) # Redirecting...
show_dashboard(True) # Welcome!
Common Mistakes
- Forgetting to Return the Wrapper: A decorator must return the internal
wrapperfunction. If you forget (return wrapper), the decorated function becomesNoneand will crash when called. - Losing Function Metadata: When you wrap a function, its
__name__and docstrings get replaced by the wrapper's info. Professional developers usefrom functools import wrapsand the@wraps(func)decorator internally to prevent this. - Wrapper Argument Mismatch: If you don't use
*args, **kwargsin your wrapper, your decorator will only work on functions with zero arguments.
Best Practices
- Use @wraps: Always use
functools.wrapsinside your decorator to preserve the original function's information. - Keep it Transparent: A decorator should add behavior, not fundamentally change what the original function was meant to do.
Practice Exercises
- The Timer: Create a decorator that prints "Time to run: 1 second" (just a static print for now) before calling the function.
- Double Result: Write a decorator that takes a function returning a number and doubles that number.
- The Greet Wrap: Create a decorator that prints "Good Morning" before the function and "Good Night" after it.