Files
054-speed-calc-decorator/docs/wiki/Step-2-Decorator-Skeleton.md
Tirsvad 0227b109d9 Add wiki in English, Danish and Bahasa Malaysia
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
2026-11-06 13:45:44 +08:00

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

Step 2: the decorator skeleton

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 wrapper is a closure; it remembers function after skeleton has returned.
  • *args, **kwargs let the wrapper accept the arguments of any function and pass them on.
  • functools.wraps keeps the original name and docstring, so the decorated function still says fast_function.
  • @name above a function is shorthand for function = name(function).