Decorators in Python
Chapter 27: Decorators
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Functions are values too
A function is a value: you can name it, pass it, store it, and even return a new function from another function.
Your first decorator: wrapping a function
A decorator is a function that takes a function and returns a wrapper that adds something before or after it, and @name above a def applies it.
Wrappers that fit any function
A wrapper written as def wrapper(args, *kwargs): accepts any arguments and passes them straight on with func(args, *kwargs), so one decorator fits every function.
Stacking decorators, settings and caching
Stacked decorators wrap from the bottom up and run from the top down, a decorator with settings needs one more layer, and @functools.cache remembers a function's answers.