Decorators and Higher-Order Functions
Master Python decorators. Learn higher-order functions, closures, the @ syntax, functools.wraps metadata preservation, decorators with arguments, and real-world logging/timing use cases.
Imagine you have a high-end wristwatch. When winter arrives, you slip on a warm jacket and a pair of leather gloves.
The watch underneath hasn’t changed at all—its internal gears still tick, and it still tells time with precision. But by wrapping yourself in outerwear, you added extra protection and warmth to your daily routine.
In Python, a Decorator is a way to wrap a function with extra behavior—like timing its performance, logging its calls, verifying user permissions, or caching its outputs—without modifying the original function’s source code.
1. The Foundation: First-Class Functions
In Python, functions are First-Class Citizens. This means functions are treated like any other variable or object:
- You can assign a function to a variable.
- You can pass a function as an argument into another function.
- A function can define and return another function!
def shout(text):
return text.upper() + "!"
# Assign function to a new variable:
yell = shout
print(yell("hello")) # HELLO!
# Pass function into another function:
def run_action(func, value):
return func(value)
print(run_action(shout, "welcome")) # WELCOME!
2. Anatomy of a Decorator
A decorator is simply a function that takes a function as an argument, defines a wrapper closure that adds behavior, and returns that wrapper:
def announce(func):
"""A simple decorator that announces execution."""
def wrapper():
print(">> Attention: Function is about to run!")
func()
print(">> Attention: Function finished execution.")
return wrapper
# Standard function
def ring_bell():
print("Ding! Dong!")
# Manually decorating ring_bell:
decorated_bell = announce(ring_bell)
decorated_bell()
Output:
>> Attention: Function is about to run!
Ding! Dong!
>> Attention: Function finished execution.
3. The Syntactic Sugar: The @ Symbol
Writing ring_bell = announce(ring_bell) is cumbersome. Python provides elegant syntactic sugar: place @decorator_name on the line directly above the function definition:
@announce
def ring_bell():
print("Ding! Dong!")
# When you call ring_bell(), it runs the decorated version automatically!
ring_bell()
The @announce syntax is 100% equivalent to writing ring_bell = announce(ring_bell).
4. Supporting Arguments with *args and **kwargs
What if the decorated function accepts parameters and returns a value?
Your wrapper must accept arbitrary arguments using *args and **kwargs (learned in args-kwargs) and explicitly return the result of func:
def trace(func):
def wrapper(*args, **kwargs):
print(f"Calling '{func.__name__}' with args={args}, kwargs={kwargs}")
result = func(*args, **kwargs) # Capture return value!
print(f"'{func.__name__}' returned: {result}")
return result # Hand result back to the caller!
return wrapper
@trace
def multiply(a, b):
return a * b
total = multiply(6, 7)
print("Final total:", total)
Output:
Calling 'multiply' with args=(6, 7), kwargs={}
'multiply' returned: 42
Final total: 42
5. The Metadata Trap and @functools.wraps
Look at what happens to a function’s name and documentation when decorated without protection:
@trace
def compute():
"""Calculates important figures."""
pass
print(compute.__name__) # 'wrapper' (Oops! Not 'compute'!)
print(compute.__doc__) # None (Lost original docstring!)
Because compute was replaced by wrapper, debugging tools, IDE autocomplete, and stack traces see only the name "wrapper".
The Fix: Always Use @functools.wraps
from functools import wraps
def trace(func):
@wraps(func) # Copies original __name__, __doc__, etc. to wrapper!
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
[!IMPORTANT] Always include
@wraps(func)inside your custom decorators. It preserves original function identity and documentation for test runners and debuggers.
6. Real-World Decorator: Execution Timer
Here is a practical, production-ready decorator that times how long any function takes to execute:
import time
from functools import wraps
def timer(func):
"""Measure and print execution duration of any function."""
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start_time
print(f"[{func.__name__}] completed in {elapsed:.6f} seconds.")
return result
return wrapper
@timer
def process_data(count):
return sum(x ** 2 for x in range(count))
result = process_data(500_000)
Output:
[process_data] completed in 0.038412 seconds.
Summary & What’s Next
- Decorators wrap and enhance function behavior without altering source code.
- Decorators rely on first-class functions and closures.
- Use
@decorator_nameabove function definitions as syntactic sugar. - Always accept
*args, **kwargsand returnresultinside the wrapper. - Always use
@functools.wraps(func)to preserve original function metadata.
Now that you know how to wrap function lifecycles, how do you manage and guarantee setup and teardown for system resources like files, locks, and network sockets? Learn about context-managers.