Skip to main content
Module 9 · Lesson 4 of 436/36 in the course~18 min
Module lessons (4/4)

Decorators: functions that wrap functions

Lesson preview5 hands-on exercises readyPython Course · Module 9 — Modern Python in practice

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 @decorator as an exact equivalence of fn = 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

  1. 11. Anatomy of a decorator without @ vs with @
  2. 22. Call tracking and timing decorator
  3. 33. Decorator Factory with Arguments (@repeat(n))
  4. 44. Instant caching with @lru_cache
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 9 — Modern Python in practice

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.