What is a closure?
A function that remembers variables from its outer scope even after the outer function has finished.
Why use closures instead of globals?
Closures provide private, safe, and reusable state; globals are shared, unsafe, and hard to debug.
What is a decorator?
A function that wraps another function to add extra behavior without modifying it.
Closure vs Decorator
Closure = concept (function remembers data)
Decorator = use-case built using closures (wraps functions)
Decorator Structure
def decorator(func):
def wrapper(args, **kwargs):
# extra work
return func(args, **kwargs)
return wrapper
What does @decorator mean?
It is syntactic sugar for:
func = decorator(func)
Why are decorators useful?
To avoid code repetition, add reusable behavior (logging, timing, retry, caching), and keep code clean.
What does a timer decorator do? @timer
Measures execution time of a function.
What does a retry decorator do?
Retries a function multiple times if it fails.
What does a cache decorator do?
Stores function results to avoid recomputation.
Why not directly use functools.lru_cache?
To understand memoization, hashing of arguments, and performance optimization.
What is the core idea behind decorators?
Add extra functionality to functions without changing their original code.