What is a decorator in Python?
A decorator is a design pattern that allows you to modify or extend the behavior of a function or class without permanently modifying its source code. In Python, functions are first-class objects, meaning they can be passed as arguments and returned from other functions.
def my_decorator(func):
def wrapper():
print("Something happens before the function.")
func()
print("Something happens after the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
![]()
Deep Dive: What say_hello Really Becomes Under the Hood
To truly master decorators, it helps to demystify the @ syntactic sugar.
When you write:
@my_decorator
def say_hello():
print("Hello!")
Python is simply performing a neat shortcut. This syntax is 100% equivalent to writing:
def say_hello():
print("Hello!")
# The decorator wraps the original function and rebinds the name
say_hello = my_decorator(say_hello)
Why Returning wrapper Makes This Work
- The Function Reassignment: When Python evaluates
say_hello = my_decorator(say_hello), it passes your originalsay_hellofunction intomy_decoratoras thefuncargument. - Returning the Wrapper: Inside
my_decorator, the inner functionwrapperis created and returned usingreturn wrapper. Notice there are no parentheses afterwrapper—we are returning the function object itself, not calling it yet. - Variable Rebinding: Because
say_hellois assigned the result ofmy_decorator(say_hello), the variable namesay_hellonow points directly to thewrapperfunction, not the originalsay_hellofunction. - Execution: Later, when you call
say_hello(), you aren't calling your original function anymore—you are executingwrapper(). Insidewrapper, it runs the pre-code, invokes the original function (using thefuncreference it remembers through closure), and runs the post-code.
A Quick Demonstration:
If you check the __name__ of your decorated function without using functools.wraps, you can see this redirection in action:
print(say_hello.__name__) # Output: wrapper (because say_hello now points to the wrapper function!)
(Tip for production code: Always use @functools.wraps(func) on your wrapper function to preserve the original function's metadata, docstrings, and name!)
Handling Function Parameters in Decorators (*args and **kwargs)
What happens when your target function needs to accept parameters—like greeting a specific user by name?
If your decorator's wrapper function doesn't accept arguments, calling say_hello("Alice") will immediately crash with a TypeError: wrapper() takes 0 positional arguments but 1 was given.
To make decorators flexible enough to handle any function signature, the wrapper must accept *args and **kwargs and pass them along to the original function.
The Complete Example
def my_decorator(func):
# wrapper now accepts *args and **kwargs to handle any input parameters
def wrapper(*args, **kwargs):
print(f"--- Log: About to run '{func.__name__}' ---")
# Execute the original function, forwarding all arguments
result = func(*args, **kwargs)
print(f"--- Log: Finished running '{func.__name__}' ---")
return result # Return the original function's return value (if any)
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
# Under the hood, Python still performs this exact rebinding:
# say_hello = my_decorator(say_hello)
# Calling the decorated function
say_hello("Alice")
What Happens Behind the Scenes Now?
- The Rebinding: When Python evaluates
@my_decorator, it runssay_hello = my_decorator(say_hello). The variablesay_hellonow points to thewrapperfunction. - Passing the Argument: When you call
say_hello("Alice"), you are actually callingwrapper("Alice"). - Catching and Forwarding:
wrappercatches"Alice"inside its*argstuple.Inside
wrapper, it executesfunc(*args, **kwargs), which unpacks and passes"Alice"down to your originalsay_hellofunction.Execution Output:
--- Log: About to run 'say_hello' ---
Hello, Alice!
--- Log: Finished running 'say_hello' ---
Using *args and **kwargs inside your wrapper ensures your decorator remains universal—meaning you can slap it onto a function with zero parameters, one parameter, or ten keyword parameters, and it will never break!