QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Advanced 20 min readModule: Module 8: Custom Decorators & Generators

Custom Function Decorators & Memory Generators (yield)

Write timing/caching decorators and stream infinite datasets with generators and the 'yield' keyword.

What You Will Learn in This Lesson

  • Writing custom decorators with functools.wraps
  • Streaming data one item at a time with yield generators
  • Memory differences: generator expressions vs list comprehensions

Introduction & Core Concept

Decorators modify function behavior without altering their source code. Generators produce items lazily on demand rather than allocating entire collections in memory.
WHY DOES THIS MATTER IN THE REAL WORLD?

Streaming a 10,000,000 row CSV with a generator uses 5KB memory instead of 4GB RAM.

Timing Decorator & Generator Stream

python
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import time
from functools import wraps
def timing(func):
@wraps(func)
def wrapper(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
print(f"[{func.__name__}] finished in {(time.time() - t0)*1000:.2f}ms")
return result
return wrapper
def number_stream(n):
for i in range(n):
yield i * i
@timing
def run():
stream = number_stream(5)
print("Generator Yields:", list(stream))
run()

Line-by-Line Technical Breakdown

1Generator expressions (x for x in data) use parentheses instead of square brackets.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[PYTHON]
PYTHON SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Use functools.wraps inside decorators to preserve docstrings and function names.

Lesson Summary & Core Takeaways

  • Decorators and generators enable clean, memory-efficient software architectures.