Module lessons (4/4)
Decorators: functions that wrap functions
Higher-order functions, @decorator syntax, functools.wraps metadata preservation, and @lru_cache.
What you'll learn in this lesson
- Understand that functions in Python are first-class objects that can be passed to and returned from other functions.
- Decipher the syntactic sugar
@decoratoras an exact equivalence offn = decorator(fn). - Write secure generic wrappers by accepting
(*args, **kwargs)and preserving identities and docstrings with@functools.wraps. - Apply built-in decorators from the standard library such as
@functools.lru_cache.
Overview
A decorator is a higher-order function that takes another input function, wraps it by adding behavior before or after the call (logging, authentication, timing, caching), and returns a new function ready to replace the original.
The @my_decorator syntax above def target(): has nothing magical about it: upon function definition (when the module is loaded!), Python executes target = my_decorator(target).
Sections covered in this lesson
- 11. Anatomy of a decorator without
@vs with@ - 22. Call tracking and timing decorator
- 33. Decorator Factory with Arguments (
@repeat(n)) - 44. Instant caching with
@lru_cache - 5Check for understanding
- 6Test yourself
Unlock "Decorators: functions that wrap functions" and the full Python Course curriculum
Higher-order functions, @decorator syntax, functools.wraps metadata preservation, and @lru_cache.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.