Sub topic 5
The @ syntax is shorthand for reassignment
This chapter assumes you can define and call functions, pass positional and keyword arguments, and write a simple nested function that returns another function. The previous chapters built the wrapper pattern by hand. Here you will see that the @ line adds no new mechanism. It is a shorter way to write a call and a rebinding you already know how to write.
The two spellings
A decorator is a callable that takes a function and returns something to use in its place. You can apply one without any special syntax:
def shout(func):
def wrapper():
return func().upper()
return wrapper
def greet():
return "hello"
greet = shout(greet)
print(greet()) # HELLO
@shout
def farewell():
return "goodbye"
print(farewell()) # GOODBYEThe greet function is defined normally, then the name greet is reassigned to whatever shout(greet) returns. The @shout line above farewell does the same two steps. The only difference is that you don't have to write the function name three times, and the decorator sits next to the def, where a reader sees it first.
| Manual form | `@` form |
|---|---|
| `def f(): ...` then `f = deco(f)` | `@deco` above `def f(): ...` |
| `def f(): ...` then `f = deco(arg)(f)` | `@deco(arg)` above `def f(): ...` |
After either form, the name greet or farewell refers to the object the decorator returned. In these examples that object is wrapper. The original function survives only because wrapper holds a reference to it through its closure.
What happens, step by step
When Python reaches a decorated def, it does the following:
- It evaluates the decorator expression, such as
shout. - It creates the function object from the
def. - It calls the decorator with that function object as its only argument.
- It binds the function's name to the value the decorator returned.
Step 4 is the important one. Python does not check what the decorator returned. It binds the name to that value, whatever it is.
Decoration happens at definition time
The decorator runs once, when the def statement executes. It does not run when you call the function. This difference between definition time and call time explains many surprises, so it is worth seeing directly:
def announce(func):
print(f"decorating {func.__name__}")
return func
print("before definition")
@announce
def work():
print("working")
print("after definition")
work()
work()The output is:
before definition
decorating work
after definition
working
workingThe message "decorating work" prints once, between the two markers, and not again on either call. The body of announce ran at the moment of definition. Only the code inside a wrapper function runs on each call.
For a module-level function, decoration happens when the module is first imported. A decorator that does something expensive or has side effects, such as opening a connection or registering a route, does that work at import time. For methods, decoration happens when the class body executes, which is also at import time for a class defined at module level.
A decorator can return anything
Because the name is bound to the returned value without a check, a decorator is free to return the original function unchanged. This is how registration decorators work: they record the function somewhere and hand it back untouched. The announce example above does this.
A decorator can also return something that is not a function at all. That is usually a bug, and the most common version is forgetting the return:
def broken(func):
print("decorating", func.__name__)
# no return statement, so the result is None
@broken
def task():
return 1
print(task) # NoneThe name task is now bound to None. The mistake shows up later, far from the cause, when you try to call it and get TypeError: 'NoneType' object is not callable. When you see that error on a function you know you defined, check the decorators above it first. Look for one that returns None or returns the result of calling the function (return func()) instead of the function itself.
The decorator expression
The text after @ is an expression. Before Python 3.9, the grammar allowed only a dotted name with an optional call, such as @shout, @functools.lru_cache or @app.route("/"). Since Python 3.9 (PEP 614), any expression is allowed:
decorators = {"loud": lambda f: (lambda: f().upper())}
@decorators["loud"]
def hello():
return "hello"
print(hello()) # HELLOThe expression decorators["loud"] is evaluated first and must produce a callable. That callable is then called with the function. This is why @repeat(times=3) works: repeat(times=3) is evaluated first and returns a decorator. The decorator is then applied to the function. Later chapters build on this rule, and it is also the source of one common mistake. Writing @repeat without the parentheses passes the function to repeat as times, and the error appears only when the function is called or defined.
On Python 3.8 and older, the decorators["loud"] form is a syntax error. Check your minimum supported version before using it in a library.
The original name is never bound
The manual form and the @ form are equivalent in the final result, but not in every intermediate detail. With the manual form, the name greet points to the original function for a moment before it is reassigned. With @, the name is never bound to the original. This has one practical consequence, which appears with recursion:
def trace(func):
def wrapper(n):
print(f"call {n}")
return func(n)
return wrapper
@trace
def countdown(n):
if n > 0:
countdown(n - 1)
return n
countdown(2)This prints:
call 2
call 1
call 0Inside countdown, the name countdown is looked up in the module at call time. By then it refers to wrapper, so every recursive call goes through the decorator. For tracing, that is what you want. For a decorator that does something expensive on each call, such as a timer that prints elapsed time, you will get one report per recursive level.
Where you can put @
The @ line is valid only directly above a def, an async def or a class statement. You cannot decorate an assignment or a lambda with it. To decorate a lambda, use the manual form:
double = lambda x: x * 2
double = shout(double) # manual form works anywhereThe @ form also works on methods inside a class body, where the decorator receives the plain function (not yet bound to an instance):
def log_call(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
class Greeter:
@log_call
def hello(self, name):
return f"hello, {name}"
print(Greeter().hello("Ada"))The wrapper is stored in the class as hello. When you call Greeter().hello("Ada"), Python binds the instance as the first argument and the wrapper receives it in *args. This works because plain functions stored in a class become methods on access. A wrapper written as a class with __call__ does not get this behavior automatically, which a later chapter covers.
Debugging decorated names
When something goes wrong with a decorated function, these checks are quick:
- Print the name. If you see
Noneor an unexpected type, the decorator did not return a function. - Print
func.__name__. If it sayswrapperinstead of the original name, the decorator did not usefunctools.wraps(the next chapter covers this). - Use the manual form temporarily. Replace
@decowithf = deco(f)after the definition, and add aprintbetween the steps.
Exercise
What does Python bind the name compute to after this code runs, and what does compute(4) print?
def doubleresult(func):
def wrapper(x):
return func(x) * 2
return wrapper
@doubleresult
def compute(x):
return x + 1
print(compute(4))
Show answer
The name compute is bound to the inner wrapper function that double_result returned, which keeps the original compute in its closure. The call compute(4) runs wrapper(4), which computes func(4) * 2. The original function returns 5, so the program prints 10. The @double_result line is the same as writing compute = double_result(compute) after the def.
Exercise
The decorator below runs without errors when the module loads. What happens when you later call process(), and what is the fix?
def register(func):
print("registered", func._name_)
@register
def process():
return "done"
process()
Show answer
The call raises TypeError: 'NoneType' object is not callable. The register function has no return statement, so it returns None, and Python binds the name process to None. The "registered process" message prints at definition time, which hides the problem. The fix is to add return func at the end of register, so the name stays bound to the original function.