Wrap Calls without Losing Results
Core idea
A decorator receives a function and returns the object bound to its name. A wrapper can run extra work before or after a call. Forward positional and keyword arguments with *args and **kwargs and return the original result. The decorator runs when the definition executes, not each time the function is called.
def trace(fn): def wrapper(*args, **kwargs): print('call') return fn(*args, **kwargs) return wrapper@tracedef total(a, b=1): return a + bprint(total(4, b=3))The keyword reaches total and its result reaches print.
Explicit rebinding
def double_result(fn): def wrapper(x): return 2 * fn(x) return wrapperdef fee(x): return x + 1fee = double_result(fee)print(fee(3))This wrapper deliberately changes the result; equivalent decorator syntax is @double_result.
Common mistake
Without return, a wrapper silently returns None. Do not catch unrelated exceptions or call the function twice unless that is the declared behavior.
Practice
Wrap a function with two keyword-only parameters and verify the returned value and exception propagation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Basic wrapper decorators
Check your understanding of basic wrapper decorators.
What is printed?
def wrap(f): return lambda x: f(x)+1@wrapdef f(x): return x*2print(f(3))What is printed?
def wrap(f): def inner(): f() return inner@wrapdef f(): return 5print(f())When is the decorator applied?
How should a generic wrapper forward keyword arguments?