Loading section...
Decorators
A decorator is a function that wraps another function, adding behavior without modifying the original. Decorators combine everything you've learned: higher-order functions, closures, and function objects. Decorators are everywhere in professional Python. Web frameworks like Flask and Django use them for routing. Testing frameworks use them for setup. Data libraries use them for caching. Understanding decorators is essential. The Decorator Pattern A decorator takes a function, creates a wrapper that adds behavior, and returns the wrapper. Let's build one step by step: The @ Syntax Practical Decorator: Timing One of the most useful decorators measures how long a function takes to execute: This pattern is extremely useful for performance profiling. Add the decorator to any function you want t