Preserve a callable contract in instrumentation
Instrumentation can damage an API when it hides metadata or changes return and exception behavior. functools.wraps preserves the wrapped function relationship so introspection can recover the original signature. Timing or logging should remain an effect around the call, not a transformation of its result.
This exercise counts completed attempts through a callback and includes failed calls. The wrapper must accept arbitrary positional and keyword arguments and should not swallow errors from the wrapped function. Static ParamSpec annotations can improve type checking in a real codebase; runtime behavior still needs its own tests.
import functools,inspect
def trace(f):
@functools.wraps(f)
def wrapped(*args,**kwargs):
return f(*args,**kwargs)
return wrapped
@trace
def add(a,b=1):return a+b
print(inspect.signature(add))Review the design
The wrapper preserves dynamic behavior and inspect.signature follows __wrapped__. An async function needs a separate async wrapper that awaits completion; wrapping only coroutine construction would record the wrong boundary.
Your task
Implement instrument(function,record) preserving metadata with wraps. Call record(function.__name__) once in finally for each attempt; return the original result and propagate its exception. record itself is assumed not to fail.
The explanation opens here once every check passes.