Practice & Assessment
Test your understanding of Advanced Python Patterns
Multiple Choice Questions
6What exception must a `__next__` method raise to signal the end of iteration?
What happens to a generator function's execution when it hits a `yield` statement?
What does returning `True` from `__exit__` do?
Why are Python threads ineffective for CPU-bound tasks?
What does `field(default_factory=list)` do in a Python dataclass?
Which is the recommended choice for downloading 100 URLs concurrently in Python?
Coding Challenges
1Lazy file line reader with generator
Write a generator function `read_large_file(filepath)` that yields one line at a time from a text file, stripped of trailing whitespace. Then write a second generator `grep(pattern, lines)` that yields only lines containing a given substring. Chain them to search a large file without loading it entirely into memory. Input: a text file path and a search string. Output: matching lines printed to stdout. Constraints: no `readlines()`, no loading the full file. Estimated time: 20-25 minutes.
Mini Project
Typed Data Pipeline with Context Manager
Build a typed CSV-to-JSON ETL pipeline. Define a `@dataclass` called `Record` with typed fields (name: str, value: float, category: str). Write a context manager class `PipelineContext` that logs start/end times and suppresses `ValueError` during transformation (logging them instead of crashing). Write a generator `read_csv_records(filepath)` that yields `Record` objects one at a time. Write a function `transform(records)` that filters records where value > 0, groups them by category into a dict, and computes per-category totals. Export the result to a JSON file. Use type hints throughout. Run the pipeline inside the context manager. Demonstrate: dataclass, type hints, generator, custom context manager, JSON export, and CSV reading.
