← Back to Python, page 5

python-0088 · Medium mid

Write a generator pipeline that processes a large log file lazily.

Chain generator functions or expressions, each consuming the previous one: read lines, parse them, filter, then aggregate. Only one line is in memory at a time, so the pipeline handles files larger than RAM, and each stage stays small and testable.

Full answer
python
from collections import Counter

LOG = [
    "2026-12-01 10:00:01 INFO /home 200 12",
    "2026-12-01 10:00:02 ERROR /pay 500 340",
    "bad line",
    "2026-12-01 10:00:03 INFO /pay 200 95",
    "2026-12-01 10:00:04 WARN /home 404 8",
]

def parse(lines):
    for line in lines:
        parts = line.split()
        if len(parts) != 6:
            continue
        date, time_, level, path, status, ms = parts
        yield {"level": level, "path": path, "status": int(status), "ms": int(ms)}

def slow(records, threshold):
    return (r for r in records if r["ms"] >= threshold)

records = parse(iter(LOG))
print(Counter(r["status"] for r in records))
print([r["path"] for r in slow(parse(LOG), 90)])

Output:

text
Counter({200: 2, 500: 1, 404: 1})
['/pay', '/pay']

parse skips malformed lines and yields dictionaries one at a time, and slow filters lazily. With a real file, parse(open(path, encoding='utf-8')) would stream lines from disk the same way. A generator can be consumed only once, which is why the second query creates a fresh parse(LOG) pipeline. The status counter shows two 200s, one 500 and one 404; the slow requests are /pay at 340 ms and /pay at 95 ms.

python
from collections import Counter

LOG = [
    "2026-12-01 10:00:01 INFO /home 200 12",
    "2026-12-01 10:00:02 ERROR /pay 500 340",
    "bad line",
    "2026-12-01 10:00:03 INFO /pay 200 95",
    "2026-12-01 10:00:04 WARN /home 404 8",
]

def parse(lines):
    for line in lines:
        parts = line.split()
        if len(parts) != 6:
            continue
        date, time_, level, path, status, ms = parts
        yield {"level": level, "path": path, "status": int(status), "ms": int(ms)}

def slow(records, threshold):
    return (r for r in records if r["ms"] >= threshold)

records = parse(iter(LOG))
print(Counter(r["status"] for r in records))
print([r["path"] for r in slow(parse(LOG), 90)])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Generators process one item at a time
  • Stages compose like Unix pipes
  • Skip bad lines rather than crash
  • Generators are single-use
  • Works on files larger than memory

Common mistakes

  • Reading the whole file with readlines()
  • Reusing an exhausted generator

Follow-ups

  • How would you count malformed lines?
  • How would you parallelise this pipeline?

Tips

  • Mention single use