wraps Preserves Decorator Metadata

functools.wraps copies __name__ and __doc__ onto the wrapper, so decorated functions keep their identity in logs, tracebacks, and help output.

PythonResilience

Code

pythonsnippet
18 lines
import functools

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(f"called {func.__name__} -> {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    """Add two numbers."""
    return a + b

# wraps 把元数据复制到包装层:装饰后仍是 add
print(add.__name__, "|", add.__doc__)
print(add(2, 3))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

add | Add two numbers.
called add -> 5
5

How it works

wraps Preserves Decorator Metadata comes down to the functions log_calls, wrapper and add.

Using it

Signature: def log_calls(func)

Running the file prints labeled results such as called — each operation’s effect is visible in the output.

The surface worth importing is log_calls; the helpers around it are private to the snippet.

Key statements

def wrapper(*args, **kwargs):
    result = func(*args, **kwargs)
    print(f"called {func.__name__} -> {result}")
    return result
def add(a, b):
    """Add two numbers."""
    return a + b

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `functools`. The file defines `log_calls`, `wrapper`, `add` at load time.