Skip to content

Generators (yield) and Streaming ​

Problem: If a file has 1 million lines of records, loading them all into memory takes a long time and uses a lot of memory.

Solution: stream them one line at a time. Instead of pouring out all the water at once, you open it a little at a time like a faucet.

python
def read_lines(path):
    """A generator that hands over a file one line at a time, in order"""
    with open(path, encoding="utf-8") as f:
        for line in f:              # without loading the whole file into memory,
            yield line              # 'stream' it one line at a time
  • A normal function returns its value all at once with return,
  • but with yield, it hands over one value, pauses, and continues from there on the next request.
python
for tx in read_lines("data/transactions.jsonl"):
    if condition(tx):
        print(tx)   # it only reads as much as needed, so it's fast and light

Requirement: implement list and search with generator-based streaming

Summary ​

ConceptSummary
GeneratorA faucet that lets water out a little at a time instead of pouring it all at once

Source: Codyssey-B1/B2-1