Decorators
Decorators
🎯 By the end of this lesson
After reading this lesson, you will be able to confidently do the following three things.
- ▸✅ Understand how higher-order functions return other functions
- ▸✅ Use the
@decoratorsyntax and understand whyfunctools.wrapsmatters - ▸✅ Apply
@lru_cache,@property, and@staticmethodin practice
Use the learning goals as a checklist, and close the lesson once you can answer all of them.
Decorators — Code + Output
@decorator = wrap a function to add functionality. Separates cross-cutting concerns like logging, caching, and authentication.
1. The simplest decorator
@log is equivalent to writing add = log(add).
2. Measuring execution time
3. Decorator with arguments
4. Commonly used built-in decorators
@property (getter), @staticmethod, and @classmethod are also frequently used in classes.
One-line summary
🐍 Try It — Decorators
🤖 How to ask AI
Knowing the concepts from this lesson lets you give AI specific instructions — not a vague 'fix this,' but a request with vocabulary. That is the starting point for saving tokens.
- ▸'Apply the functools.lru_cache decorator to this function'
- ▸'Create a timing and logging decorator using functools.wraps'
Why this reduces tokens
Without the concepts, you have to ask 'What does that mean?' after every AI response. Those follow-up questions eat tokens. Learn the concept once and the conversation ends in a single exchange.