Q&A-1Explain decorator evaluation, application, and call-time execution as separate phases.
Answer
Three phases, three different times. Evaluation: the decorator expression is evaluated when the def statement executes. At import for a module-level function, or when the enclosing function runs for a nested one. Application: the resulting callable is invoked once with the function object, and its return value is rebound to the original name. Call time: whatever is now bound to that name runs on every call.
import functools
def traced(fn):
print(f"apply {fn.__name__}") # application phase
@functools.wraps(fn)
def wrapper(*a, **kw):
print(f"call {fn.__name__}") # call-time phase
return fn(*a, **kw)
return wrapper
print("A: before def")
@traced
def add(a, b):
return a + b
print("B: after def")
add(1, 2)
add(3, 4)Output:
A: before def
apply add
B: after def
call add
call addapply add prints once, between A and B: that is application, and it happened before any call. The two call add lines are call time. @traced is exactly add = traced(add); the traced name is looked up at evaluation, traced(add) runs at application.
| phase | when | count | what executes |
|---|---|---|---|
| evaluation | def statement executes | once per execution | decorator expression, e.g. route("/x") |
| application | same statement, immediately after | once | traced(add); result bound to add |
| call time | each add(...) | per call | wrapper body; may or may not call fn |
Stacked decorators: @a over @b over def f evaluates a then b top-down, but applies bottom-up. f = a(b(f)).
Failure modes worth naming:
- Import-time side effects. A registry decorator
@route("/x")writes to a module-level dict once, at import. Assume it runs per call and you will double-register onimportlib.reload, or ship a half-populated registry when import fails partway. Detect by asserting registry size after import and after a reload. - State captured at application time is process-wide. A cache dict created inside the decorator body is one object for the process lifetime.
functools.lru_cache(maxsize=None)on a function with unbounded distinct arguments grows without bound: a leak, not a cache. Watchcache_info().currsizeandmisses. - Missing
functools.wraps.add.__name__becomes"wrapper"andinspect.signatureno longer reflectsadd. Frameworks that dispatch on name or signature break silently.wrapscopies__module__,__name__,__qualname__,__doc__,__dict__and sets__wrapped__. - Async splits call time again. Calling an
async deffunction returns a coroutine without running the body; the body runs atawait. So anasync def wrapperlogs at await, not at call: timing placed there measures await, not invocation.
Alternatives and cost: writing add = traced(add) by hand is the same thing without the syntax; a class-based decorator is worth it when you need per-instance state or __get__; contextlib.ContextDecorator lets one object serve as both decorator and context manager. The cost is one extra Python frame per call, which matters in hot inner loops: there, inline the logic or push it to a C-level mechanism instead.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.