Combine Typed Decorators and Metadata
Core idea
A transparent decorator should preserve both the callable type contract and useful introspection. ParamSpec and a return TypeVar communicate the signature to a checker; functools.wraps preserves selected metadata and an unwrapping link. A result-changing wrapper must declare its new return type instead.
from functools import wrapsfrom typing import Callable,ParamSpec,TypeVarP=ParamSpec('P'); R=TypeVar('R')def traced(fn:Callable[P,R])->Callable[P,R]: @wraps(fn) def inner(*args:P.args,**kwargs:P.kwargs)->R: return fn(*args,**kwargs) return inner@traceddef total(n:int, *, fee:int=1)->int: return n+feeprint(total.__name__,total(4,fee=2))The runtime wrapper forwards arguments and metadata; the type signature communicates the relationship separately.
Advertise a changed return type
from typing import Callable,ParamSpec,TypeVarP=ParamSpec('P'); R=TypeVar('R')def stringify(fn:Callable[P,R])->Callable[P,str]: def inner(*args:P.args,**kwargs:P.kwargs)->str: return str(fn(*args,**kwargs)) return inner@stringifydef count(n:int)->int: return n+1result=count(5)print(result,type(result).__name__)The wrapper returns a string, so the public static result is str.
Common mistake
wraps alone is not a type contract. Conversely, typed forwarding alone does not preserve metadata. Do not copy annotations blindly when changing the return type.
Practice
Build a transparent wrapper and a result-changing wrapper; verify keyword-only calls, return types and name separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed decorators
Check your understanding of typed decorators.
What is printed?
from functools import wrapsdef f():return 3@wraps(f)def g():return "x"print(g.__name__,g())What is printed?
def text(f): return lambda x: str(f(x))print(type(text(lambda x:x+1)(3)).__name__)What should a decorator returning str advertise?
What does wraps preserve separately from typing?