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
pythonpython
12345678910111213141516171819202122import timefrom functools import wrapsdef 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 resultreturn wrapperdef number_stream(n):for i in range(n):yield i * i@timingdef 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 CodeIndustry 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.