Sub topic 4
The problem: decorators hide the original function
This chapter assumes you can write a basic decorator with the @ syntax and know that functions are objects you can pass around and return. The earlier chapter on decorators covers both.
What a decorator really does
This line:
@log_calls
def greet(name): ...means the same as this:
def greet(name): ...
greet = log_calls(greet)After the decorator runs, the name greet points at whatever the decorator returned. That is usually an inner function, often called wrapper. The original function still exists, but only inside the wrapper's closure.
A naive decorator
Here is a logging decorator with no special handling:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def greet(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__)
print(greet.__doc__)The output is:
calling greet
Hello, Ada
wrapper
NoneThe call works and the logging works. But greet.__name__ is now "wrapper", and the docstring is gone, because __doc__ belongs to the function object that greet now refers to. That object is wrapper, which has no docstring.
What gets lost
Several attributes describe a function. A plain wrapper does not copy them from the original.
| Attribute | Original `greet` | Naive wrapper |
|---|---|---|
| `__name__` | `greet` | `wrapper` |
| `__qualname__` | `greet` | `log_calls.<locals>.wrapper` |
| `__doc__` | `Return a greeting.` | `None` |
| `__module__` | module of `greet` | module where the wrapper was defined |
| `__dict__` | the function's custom attributes | empty |
The signature is lost too. Tools that inspect it see only the wrapper's *args, **kwargs:
import inspect
print(inspect.signature(greet)) # (*args, **kwargs)The original signature was (name). The wrapper does not enforce it. A wrong call fails inside the original function instead, with a message that points at the wrapper.
Why it matters in practice
This looks cosmetic, but real tools read this metadata:
- Debugging. Logs and tracebacks show
wrapperfor every decorated function, so you cannot tell which one failed. - Documentation.
help(greet)and generators such as Sphinx show an empty docstring and a generic signature. - Name-based registries. Some frameworks use
__name__as a key. Web frameworks that register routes by function name see several functions all calledwrapperand report a collision. - Introspection. Code that inspects signatures, such as argument-injection or validation helpers, cannot see the real parameters.
- Testing. Doctest finds examples through
__doc__, so a lost docstring means its examples never run.
The collision case is easy to reproduce. Two decorated functions end up with the same name:
def log_calls(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
@log_calls
def subtract(a, b):
return a - b
names = {add.__name__, subtract.__name__}
print(names) # {'wrapper'}Two different functions collapse into one name. Any dictionary keyed by __name__ would keep only one of them.
The cause
Nothing in Python copies metadata automatically. The decorator creates a new function object, and a new function object has its own __name__ and __doc__. You could fix this by hand:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapperThis fixes two attributes. It forgets __qualname__, __module__, and __dict__. It also does not record where the original function lives, and it must be repeated in every decorator you write. The standard library solves this with functools.wraps, which is the next chapter.
Exercise
A decorator returns an inner function named wrapper and does nothing else to it. After decoration, what does __name__ return for the decorated function, and why?
Show answer
It returns "wrapper". The decorator syntax rebinds the original name to whatever the decorator returned, which is the wrapper function object. That object has its own __name__, and nothing copies the original's name onto it.
Exercise
Name two tools or situations where the missing docstring or signature of a decorated function causes a visible problem.
Show answer
Any two of these: help() shows no docstring and a generic (*args, **kwargs) signature, documentation generators produce empty entries, doctest never finds the examples, and frameworks that key on __name__ see several functions as the same name.