Back
+15 XP
Concept

Preserving Metadata with @functools.wraps

Decorating a function replaces it with `wrapper`, hiding its original `__name__` and docstring. Use `@functools.wraps(func)` to preserve function identity 🛡️.

python
import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@logger
def compute(x):
    """Calculates square."""
    return x * x

print(compute.__name__)  # 'compute' (not 'wrapper') 🏷️

# 35. Preserving Metadata with @functools.wraps Decorating a function replaces it with `wrapper`, hiding its original `__name__` and docstring. Use `@functools.wraps(func)` to preserve function identity 🛡️. ```python import functools def logger(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"Calling: {func.__name__}") return func(*args, **kwargs) return wrapper @logger def compute(x): """Calculates square.""" return x * x print(compute.__name__) # 'compute' (not 'wrapper') 🏷️ print(compute.__doc__) # 'Calculates square.' 📜 ``` Without `@functools.wraps`, debuggers, IDE intellisense, and documentation generators will see the generic wrapper name instead of your real function! 🛡️ --- ### Question What happens to `func.__name__` if you decorate without `@functools.wraps`? 🧠 - [ ] a. It turns into 'wrapper', masking the true identity of the function 🎭 - [ ] b. It raises an immediate AttributeError during module loading - [ ] c. It encodes the original function name in MD5 hex - [ ] d. It resets the function name to None --- ### Challenge Create a decorator `debug_call(func)` that uses `@functools.wraps(func)` and prints `f'Calling {func.__name__}'` before returning `func(*args, **kwargs)`. Decorate `def greet(name): return f'Hi {name}'`. Print `greet.__name__` and `greet('Dev')`. 🎯 <details> <summary>Solution</summary> ```python import functools def debug_call(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") return func(*args, **kwargs) return wrapper @debug_call def greet(name): return f"Hi {name}" print(greet.__name__) print(greet("Dev")) ``` </details>

Checkpoint

What happens to `func.__name__` if you decorate without `@functools.wraps`? 🧠

Practice

Create a decorator `debug_call(func)` that uses `@functools.wraps(func)` and prints `f'Calling {func.__name__}'` before returning `func(*args, **kwargs)`. Decorate `def greet(name): return f'Hi {name}'`. Print `greet.__name__` and `greet('Dev')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks