Decorators and function wrapping
A decorator accepts a function and returns the function or a replacement with added behavior.
How it works
Trace the two times code runs. The decorator takes the original function when Python creates it. The wrapper’s body runs later, whenever you call the decorated name. In the example, the later call logs the function name and then returns 8 from double.
Walk through an example
A wrapper can record a call and then call the original with the same arguments. @logged above def greet is equivalent to assigning greet = logged(greet) after defining it.
What to watch for
A wrapper should pass arguments through and return the original result unless changing the result is its purpose. functools.wraps preserves useful metadata.
Code example
from functools import wraps
def logged(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
print("Calling", fn.__name__)
return fn(*args, **kwargs)
return wrapper
@logged
def double(n):
return n * 2
print(double(4))Check your understanding
What value reaches its caller?
See the example and explanation
- Worked example
- Given
A wrapper calls original(), which returns 8, but omits return. - Answer
None
The wrapper completes without returning a value, so Python supplies None.