Use generators to keep pipelines bounded
Produce values lazily without hiding errors or resources.
Understand when work runs
A generator function executes when it is iterated, not when the generator object is created. That can move errors later than a caller expects. Document the iteration contract and avoid a generator when the caller needs an immediate validation result.
Keep resource ownership clear
If a generator opens a file, it may hold the file while a caller pauses iteration. Prefer a context manager around the iteration or make the generator accept an already-open stream. Do not assume a partially consumed generator will promptly close resources in every environment.
def parsed_rows(source):
for number, line in enumerate(source, 1):
yield number, parse(line)
with open(path, encoding='utf-8') as source:
for number, row in parsed_rows(source):
save(row)
Test partial consumption
Test the first item, an error in a later item, and early termination. If a pipeline batches writes, ensure an early failure does not silently discard a partially filled batch. The memory advantage is real only if downstream consumers avoid collecting every item.
Check your understanding
When does a generator function's body run?
Show explanation
As the caller iterates over it, not when the generator object is created.
You can read for free. Create an account to save your progress.
← Previous lesson: Transform data without loading everything Next lesson: Keep Python type hints honest →Put this lesson into practice
A practice activity at this level in the same module.
Try: Stream a large file without loading itFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.