Six pages and a sidebar, each lecture step with its screenshot and what it taught; review record RC-008. Refs #14 Refs #15 Refs #16 Refs #17 Refs #18
1.1 KiB
1.1 KiB
Step 2: the decorator skeleton
English · Dansk · Bahasa Malaysia
A decorator is a function that takes a function and returns another function. This skeleton only announces the call:
def skeleton(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
print(f"calling {function.__name__}")
return function(*args, **kwargs)
return wrapper
Run it with python -m speed_calc.lecture_steps 2.
What we gained
- Functions are values: you can pass them to other functions and return them.
- The inner
wrapperis a closure; it remembersfunctionafterskeletonhas returned. *args, **kwargslet the wrapper accept the arguments of any function and pass them on.functools.wrapskeeps the original name and docstring, so the decorated function still saysfast_function.@nameabove a function is shorthand forfunction = name(function).
