Preserve Metadata with wraps
Core idea
Wrapping a function creates a different callable. functools.wraps copies selected metadata and sets wrapped to the wrapped function. Tools such as inspect.signature normally follow that link. It does not enforce the original signature or types at runtime.
from functools import wrapsdef traced(fn): @wraps(fn) def inner(*args, **kwargs): return fn(*args, **kwargs) return inner@traceddef label(n): return f'ID-{n}'print(label.__name__, label(2))The name is copied while the call goes through inner.
Inspect the original
from functools import wrapsfrom inspect import signaturedef decorate(fn): @wraps(fn) def inner(*args, **kwargs): return fn(*args, **kwargs) return inner@decoratedef price(units, rate=2): return units * rateprint(signature(price))print(price.__wrapped__(3))Introspection follows the link; direct access bypasses the wrapper.
Common mistake
Do not treat wraps as an access-control mechanism or a type checker. The wrapper must still implement correct forwarding.
Practice
Remove @wraps and compare name and signature, then restore it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Wraps and metadata
Check your understanding of wraps and metadata.
What is printed?
from functools import wrapsdef f(): return 4@wraps(f)def g(): return 9print(g.__name__, g())What is printed?
from functools import wrapsdef f(): return 2@wraps(f)def g(): return 8print(g.__wrapped__())Which link lets introspection find the original?
What does wraps guarantee?