Module 10
Protocols and Advanced Iteration
// Lessons
5
// Quiz questions
75
// Reading time
150 min
// Exam length
15 Q
// Coding exercises
9
- 1The Iterator ProtocolImplement __iter__ and __next__, handle StopIteration signals, and make custom objects iterable. 30 min 15 questions
- 2Generator Functions & yieldSuspend execution states, stream infinite sequences lazily, and delegate streams with yield from. 30 min 15 questions
- 3Custom Context ManagersGuarantee file and lock cleanup using the __enter__ and __exit__ protocol or contextlib decorators. 30 min 15 questions
- 4Itertools Stream CombinatorsCombine, slice, group, and cycle infinite or large data streams with zero memory duplication. 30 min 15 questions
- 5Type Hints & Static VerificationAnnotate function signatures, express union generics, and validate codebase correctness with mypy. 30 min 15 questions
Coding practice: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (4 exercises)
Coding practice needs an account. Sign in or create a free ID to run these exercises.
Lab 1: Generator countdown
Write a generator function down_to_zero(n) that yields numbers from n down to 0. Print: [3, 2, 1, 0].
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 2: Header context manager
Using @contextlib.contextmanager, create a manager bracket(name) that prints [{name}] before and [/{name}] after. Test with with bracket("AUDIT"): print("logged").
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 3: Itertools cycle & islice
Use itertools.cycle([1, 2]) and itertools.islice to take the first 5 elements. Print: [1, 2, 1, 2, 1].
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 4: Annotate divider
Define def divide(a: float, b: float) -> float: return a / b. Test with divide(10.0, 4.0) and print: Result: 2.5.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
References & Further Reading
Related entries from PyLabs's own reference library.