Python Basics
Decorators Deep Dive in Python
Agenda – Python Basics - Day 7
• What are decorators?
• Why use decorators?
• Writing custom decorators
• Argument-based decorators
• Chained decorators
• Activities: Logging and caching decorators
Decorator
• Technical Definition:
A decorator is a design pattern that allows you to modify or extend
the behavior of functions or classes without permanently modifying
their structure. In Python, decorators are implemented as higher-order
functions that take a function as input and return a modified function.
• Original Function→ Decorator → Enhanced Function
• A decorator in Python is a function that modifies the behavior of
another function without changing its code.
Why Use Decorators?
• Add functionality to existing code without modifying it
• Clean, readable way to apply cross-cutting concerns (e.g.,
logging, caching, auth)
• Reusable and modular
Argument-based decorators
• Three-Layer Structure: Decorators with arguments require
an additional layer - a decorator factory that returns the
actual decorator. This creates a three-layer nested function
structure.
• Decorator Factory → Decorator → Wrapper → Enhanced
Function
Chained decorators
• Execution Order:
When multiple decorators are applied to a function, they are
executed from bottom to top (closest to the function first), but
their wrapper functions execute from top to bottom during
function call.
Activities: Logging and caching decorators
• Jump to Notebook for this activity.
Q&A
THANK YOU