Sub topic 5
The @ syntax is shorthand for reassignment
This chapter assumes you can write a basic decorator: a function that takes a function, defines a closure around it, and returns the closure. Here you will see exactly what the @ line does, and when it does it.
The @ line is an assignment
Here is a decorator applied by hand and then with @:
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 two styles do the same thing. Writing @shout above def farewell() is the same as writing farewell = shout(farewell) right after the function body. Nothing else happens. The decorator is an ordinary function call, and the name is rebound to whatever the call returns.
What happens, in order
When Python runs a decorated def, it takes these steps:
- It evaluates the decorator expression (
shout). - It creates the function object from the
defbody. - It calls the decorator with that function object.
- It binds the function's name to the value the decorator returned.
The original function is not destroyed. The wrapper holds a reference to it through its closure, which is how func() still works inside wrapper.
Decoration runs once, at definition time
The decorator call happens when the def statement executes, not when you later call the function. This example makes the timing visible:
def announce(func):
print(f"decorating {func.__name__}")
return func
@announce
def hello():
print("hello")
print("defined")
hello()
hello()The output is:
decorating hello
defined
hello
hellodecorating hello prints once, before defined. Setup work that belongs in the decorator body, such as registering the function somewhere, runs at import time. Work that belongs on every call must go inside the wrapper.
The name is rebound to the return value
Because @ is plain assignment, the name ends up bound to whatever the decorator returns. That value does not have to be a function. If you forget the return, the name is bound to None:
def broken(func):
print("decorating")
# missing: return wrapper or return func
@broken
def work():
return 1
print(work) # None
work() # TypeError: 'NoneType' object is not callableThe error appears at the call site, far from the real mistake. If you see 'NoneType' object is not callable on a decorated function, check that the decorator returns something.
Where the decorator expression can come from
The expression after @ is evaluated like any other name lookup. It can be a plain name, a dotted attribute such as @functools.lru_cache, or a call such as @repeat(times=3). In the call form, the call runs first and its result is then used as the decorator. Later chapters build on that.
Decorators also work on methods inside a class body, because a def there is the same statement:
class Greeter:
@shout
def hello(self):
return "hi"This particular example would fail when called, because shout's wrapper accepts no arguments and self is passed automatically. A decorator that forwards *args and **kwargs avoids this problem.
Exercise
Rewrite the following code without the @ syntax so it behaves the same. Then say when the "registering" message prints. def register(func): print("registering", func._name_) return func @register def task(): pass
Show answer
Use def task(): pass followed by task = register(task). The message "registering task" prints once, when the def statement runs (at import time for a module), before task is ever called.