Skip to the solution
MediumDSA12 min read

How do generator pipelines stream data lazily?

990 views

The problem

Question presented to candidate: "Say you need to process a 50 GB log file: read lines, keep the errors, parse them, and count by type. How would you do it with generators, and why does that not run out of memory?"

What a strong answer should cover:

  • A pipeline is a chain of generators, each consuming the previous one: count(parse(errors(read(f)))). Building the chain runs nothing; the final consumer pulls one item at a time through every stage.
  • Memory is constant in the input size β€” only the current item (plus any per-stage state) is alive β€” versus a list-based version that materialises every intermediate stage.
  • Laziness enables infinite sources and early termination: islice, any, next and break stop pulling, so upstream work that is not needed never happens.
  • Trade-offs: generators are one-shot, errors surface when an item is pulled (not when the pipeline is built), cleanup needs close()/with, and per-item Python call overhead makes them slower than a vectorised or list approach for small data.
  • Tools: generator functions, generator expressions, itertools (islice, chain, tee), and yield from for composing stages.

Clarifying questions expected:

  • Does the output need to be ordered, or can stages run in parallel (which generators alone do not give you)?
  • Will the data be read once or several times (one-shot iterators vs. re-reading the source)?

Code / implementation expected: Yes β€” a three- or four-stage generator pipeline over a file-like source, ideally showing that items flow one at a time.

  • generators
  • pipeline

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA traced log pipeline: lazy stages vs eager lists
PythonInfinite sources, early termination and flat memory
PythonPipeline gotchas: one-shot, late errors, cleanup, tee, late binding

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 54 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

Why does 0.1 + 0.2 != 0.3 in Python, and when do you use Decimal or Fraction?

Continue