How do you preserve a decorated function's original SIGNATURE (parameter names, defaults) for introspection tools, beyond what functools.wraps alone provides?
Short answer
functools.wraps copies __name__/__doc__/__module__ but the wrapper's ACTUAL call signature (as seen by inspect.signature()) is still `(*args, **kwargs)` unless you also explicitly copy or reconstruct the __wrapped__ attribute (which wraps() DOES set) — inspect.signature()…
Advertisement
AModel answer
functools.wraps copies __name__/__doc__/__module__ but the wrapper's ACTUAL call signature (as seen by inspect.signature()) is still `(*args, **kwargs)` unless you also explicitly copy or reconstruct the __wrapped__ attribute (which wraps() DOES set) — inspect.signature() automatically follows __wrapped__ to find the TRUE original signature.
import inspect, functools
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@logged
def add(a: int, b: int) -> int:
return a + b
print(inspect.signature(add)) # '(a: int, b: int) -> int' -- correctly follows __wrapped__Real-world example
Ensuring IDE autocomplete and documentation tools correctly show a decorated function's real parameter list, not '(*args, **kwargs)'.
Likely follow-ups
- How does inspect.signature() actually use the __wrapped__ attribute internally to find the true original signature?
Related topics