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 with attributes. The goal is to see exactly what a decorator takes away from the function it wraps. The next chapter fixes that with functools.wraps. First you need to see the damage, because the same damage shows up in logs, help output, registries, and framework errors.
What a decorator really does
The @ line is shorthand for rebinding a name:
@log_calls
def greet(name):
...
# is exactly the same as:
def greet(name):
...
greet = log_calls(greet)After the second line runs, the name greet no longer points at the function you wrote. It points at whatever log_calls returned. In a typical decorator, that is a new inner function called wrapper. The original function survives only inside the wrapper's closure.
Python does not copy the original's identity onto the wrapper. The wrapper is a separate function object with its own name, docstring, and signature. Those belong to wrapper, not to greet.
A naive decorator, step by step
Here is a standard logging decorator with no metadata handling:
import inspect
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def greet(name: str) -> str:
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__)
print(greet.__qualname__)
print(greet.__doc__)
print(greet.__module__)
print(greet.__annotations__)
print(inspect.signature(greet))
print(hasattr(greet, "__wrapped__"))Running it prints:
calling greet
Hello, Ada
wrapper
log_calls.<locals>.wrapper
None
__main__
{}
(*args, **kwargs)
FalseThe call itself works. Every identifying attribute is wrong:
__name__iswrapper, notgreet.__qualname__islog_calls.<locals>.wrapper. The<locals>part marks a function defined inside another function.__doc__isNone. The wrapper has no docstring of its own, and Python does not look at the wrapped function.__annotations__is empty, so thestrhints are gone.inspect.signaturereports(*args, **kwargs). The real parameter,name, is invisible.- There is no
__wrapped__attribute, so tools cannot walk back to the original.
The __module__ value happens to be right here only because the decorator and the function live in the same file. If log_calls came from another module, greet.__module__ would name that module instead.
What gets lost
| Attribute | Value on a naive wrapper | Who relies on it |
|---|---|---|
| `__name__` | `"wrapper"` | Logging, registries, error messages |
| `__qualname__` | `"log_calls.<locals>.wrapper"` | `repr`, pickling, test reports |
| `__doc__` | `None` | `help()`, doctest, documentation generators |
| `__module__` | The decorator's module | Pickling, documentation tools |
| `__annotations__` | `{}` | `typing.get_type_hints`, validation libraries |
| `__dict__` | Wrapper's own, empty | Code that marks functions with custom attributes |
| `__wrapped__` | Missing | `inspect.signature`, `inspect.unwrap` |
A wrapper also does not copy __defaults__ or __kwdefaults__. Introspection tools usually reach those through inspect.signature, which is why the missing __wrapped__ matters.
Where this hurts in practice
help() and documentation
help(greet) is the first place people notice. Instead of greet(name: str) -> str and the docstring, you see:
help(greet)Help on function wrapper in module __main__:
wrapper(*args, **kwargs)Documentation generators such as Sphinx and IDE tooltips read the same attributes. Every decorated function in your public API turns into an anonymous wrapper(*args, **kwargs) with no description.
repr and debugging
The default repr of a function uses __qualname__:
print(greet)
# <function log_calls.<locals>.wrapper at 0x...>If you log or print decorated callables, every one reads log_calls.<locals>.wrapper, and you cannot tell which function you are looking at. Many functions decorated by the same decorator look identical.
A traceback is different. It shows the name stored in each frame's code object, not __name__. A naive wrapper therefore shows up as wrapper in a traceback, and a correctly written one also shows up as wrapper. Metadata copying improves repr, help, and introspection. It does not rename frames in tracebacks.
Registries keyed by name
Plugin systems, command tables, and web frameworks often store functions under func.__name__. With a naive decorator underneath, every entry gets the same key:
def log_calls(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
commands = {}
def command(func):
commands[func.__name__] = func
return func
@command
@log_calls
def start():
return "starting"
@command
@log_calls
def stop():
return "stopping"
print(list(commands))
print(commands["wrapper"]())This prints:
['wrapper']
stoppingBoth commands registered under wrapper. The second overwrote the first, and start is unreachable by name. No error is raised. Flask raises an error for the same situation, because it derives a route's endpoint name from the view function's __name__ and refuses duplicates. In your own registry code you get a silent overwrite.
Type hints and custom attributes
Libraries that read annotations see a wrapper with none:
import typing
print(typing.get_type_hints(greet)) # {}Custom function attributes also disappear, because the wrapper has its own __dict__:
def log_calls(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def public(func):
func.is_public = True
return func
@log_calls
@public
def status():
return "ok"
print(hasattr(status, "is_public")) # FalseThe public decorator set the flag on the original function. The outer log_calls then replaced that function with a wrapper that never received the flag. Code that checks status.is_public now gets the wrong answer.
Callable objects have it worse
A decorator does not have to return a function. If it returns an instance of a class with __call__, the result is not a function at all, and it may lack __name__ entirely:
class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@CountCalls
def ping():
"""Say ping."""
return "pong"
print(ping())
print(ping.count)
print(ping.__doc__)
try:
print(ping.__name__)
except AttributeError as exc:
print(f"AttributeError: {exc}")The output is:
pong
1
None
AttributeError: 'CountCalls' object has no attribute '__name__'Here ping.__doc__ is None because the lookup finds the docstring of the CountCalls class, which has none. The original docstring is stored nowhere the instance exposes. Code that expects any callable to have __name__ crashes with an AttributeError. Class-based decorators need the same metadata handling as function-based ones.
The manual fix, and why it is not enough
You can copy attributes onto the wrapper 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 repairs __name__ and __doc__. It still leaves __qualname__, __module__, __annotations__, and __dict__ wrong, and it adds no __wrapped__. Each decorator you write would need the same list of assignments, and it is easy to forget one. A repeated, error-prone task like this is what the standard library helper in the next chapter is for.
Checking your own decorators
A quick test finds this problem in any decorator. Decorate a function that has a docstring, a type hint, and a custom attribute, then run these checks:
import inspect
def audit(func):
print("name:", func.__name__)
print("doc:", func.__doc__)
print("annotations:", func.__annotations__)
print("signature:", inspect.signature(func))
print("has __wrapped__:", hasattr(func, "__wrapped__"))Call audit(your_decorated_function). If the name is wrapper, the doc is None, or the signature is (*args, **kwargs) for a function with real parameters, the decorator is hiding the original.
Summary of the failure
A decorator replaces a function with a different object, and the replacement keeps its own metadata. Reading __name__, __doc__, or __annotations__ gives you the wrapper's values. Anything that identifies, documents, or inspects a function sees the wrapper.
Exercise
Given a naive decorator timed that defines an inner function wrapper(*args, **kwargs) and returns it, what do compute.__name__ and compute.__doc__ return after decorating compute, which has the docstring "Add numbers."? Why?
Show answer
compute.__name__ returns "wrapper" and compute.__doc__ returns None. The line @timed rebinds the name compute to the object returned by timed, which is the inner wrapper function. That function has its own name and no docstring, and nothing copies the original's metadata onto it.
Exercise
A command registry stores functions with registry[func.__name__] = func. Two functions, build and deploy, are each decorated with a naive logging decorator before being registered. What does list(registry) return, and which functions can you still look up?
Show answer
list(registry) returns ['wrapper']. Both functions are wrapper functions named "wrapper", so they register under the same key. The second registration (deploy) overwrites the first, so only one command is reachable, and Python raises no error.
Exercise
A decorator is written as a class with __init__(self, func) and __call__. Without extra handling, what happens when code reads decorated.__name__ on an instance, and why does the __doc__ come back as None even though the original function had a docstring?
Show answer
Reading __name__ raises AttributeError: 'CountCalls' object has no attribute '__name__', because instances of an ordinary class do not have a __name__ attribute (only the class itself does). __doc__ is looked up on the instance, then on its class. The class has no docstring, so the result is None. The original function's docstring is stored only on self.func, which no lookup of __doc__ consults.