Lazy Python code delays computation until a result is actually needed, while eager code computes everything up front. To convert eager code, identify what each step produces, replace immediate list building with generators or iterator pipelines, wrap expensive attribute or network access in property, cached_property, or callables, and only materialize results at the boundary where a caller demands a real collection. The key condition: laziness pays off when later results are often skipped or the full input never arrives, and it costs you clarity, repeatability, and some error timing.
Laziness isn't a single technique; it's a design posture. You're choosing when work happens, who triggers it, and how many times it runs. Python hands you several levers for that choice: generator functions and generator expressions, the itertools module, callables and higher-order functions, descriptors like property/cached_property, lazy imports, and lazy libraries or ORMs that defer SQL and file I/O. This article walks through the levers, the conversion workflow, the trade-offs, and the failure modes that bite people who over-apply the idea.
What Eager and Lazy Actually Mean in Python
Eager evaluation means Python computes a value at the moment it encounters the expression. [x * 2 for x in range(10)] allocates a ten-element list immediately. open(path).read() pulls the whole file into memory. A function call runs its body as soon as it's invoked. Most everyday Python is eager, and that's usually fine: eager code is predictable, easy to debug, and easy to re-read.
Lazy evaluation defers that computation until something asks for the value. (x * 2 for x in range(10)) creates a generator object that does almost nothing until you iterate it. The work happens once per element, and it stops when you stop consuming. Lazy evaluation changes when and how often work happens, not just whether it happens.
A useful mental model: eager code produces values, lazy code produces recipes for values. The recipe is free (or nearly free) to create, and you pay only when you cook.
There's a middle ground too. functools.cached_property is lazy on first access and eager on subsequent reads. range(10**9) is lazy in memory but not in cost when you sum it. "Lazy" is rarely a binary property; it's a spectrum of deferral.
Why Defer Work: Conditions Where Laziness Pays Off
Laziness earns its keep under specific conditions, and it's wasteful outside them. Use it when any of these holds:
You may not need all the results. If a pipeline stops early (searching for the first match, any(), next(), takewhile), lazy code skips the work it never needs. The input is too large for memory. Streaming a multi-gigabyte log line by line beats loading it whole. Producing a result is expensive. Database queries, HTTP calls, parsing, and heavy computation benefit from not running until demanded. The input is infinite or unbounded. You can't eagerly build an infinite list, but a generator handles it naturally. Results are expensive to keep but cheap to recompute. A memoized function that rarely repeats a key is a lazy cache.
The flip side: laziness is not a good default for small collections you'll traverse multiple times, for code where the eager version is clearer, or for anything where error timing matters and you need failures to surface at construction time. A generator that raises on its third element raises only when someone reaches the third element—which might be far from where the bug was introduced.
Prerequisites Before You Refactor
Before changing working code, line up four things so you can prove the conversion works.
First, behavioral tests that pin down outputs and ordering. Laziness changes evaluation order and timing; tests catch both. If your function returns a list, write tests asserting the same list contents, and add one test that asserts whether the result is a list or an iterator if the API contract depends on it.
Second, a memory or timing baseline if the point of the change is performance. Measure wall time and peak memory for the eager version on realistic input sizes. Without a baseline, "it's faster now" is a feeling, not a result.
Third, a clear contract for what the function should return. A function returning list[str] is a public promise. A function returning an Iterator[str] is a different promise, and callers who need len(), indexing, or repeated iteration will break. Decide deliberately which one you're shipping.
Fourth, identify all call sites of the function you're changing. A generator can be safely swapped only if no caller relies on list-specific behavior. Use grep-style search or your editor's find-references; this is the step people skip, and it's the step that causes production breakage.
Core Recipe: Convert Eager Pipeline Steps One at a Time
This procedure works whether you're converting a single function or a whole pipeline. Work through the steps in order.
1: Map the current data flow. Write down each stage: where input comes from, what each transformation produces, where the result is consumed. Mark which stages allocate a collection ([...], .append() in a loop, .sort() on a list).
2: Pick one leaf-to-root conversion. Start at the stage whose output is consumed exactly once, or the stage that allocates the most memory. Don't convert everything at once; you want a single testable change.
3: Replace eager comprehensions with generator expressions. [f(x) for x in data] becomes (f(x) for x in data). If the body is more than an expression, write a generator function with yield instead.
4: Stop accumulating inside loops. A loop that builds a list with .append() and then returns it becomes a generator function where .append() is replaced by yield.
5: Swap list-shaped itertools patterns for iterator versions. itertools.islice instead of slicing a list; chain instead of + on lists; groupby (which returns iterators) noted for its one-pass semantics.
6: At the boundary where a caller truly needs a collection, materialize explicitly. list(gen), tuple(gen), sorted(gen), set(gen), or ''.join(gen). This is your "pay here" line, and later readers will thank you for making it obvious.
7: Run the behavioral tests. If they pass, add a test asserting the new return's iterability and one-pass behavior. If they fail, use the failing test's input to trace where you assumed a collection but passed a generator.
8: Compare the memory/timing baseline. Confirm the change actually helped and didn't just move cost around. Measure the materialization point separately from the generator construction, so you can describe both.
Success check: the tests pass, the return type matches your documented contract, and no caller unexpectedly gets an exhausted iterator. Failure check: a caller errors with TypeError: object of type 'generator' has no len() or StopIteration outside a loop, or silently gets empty results because it iterated the same generator twice. Those errors mean you missed a materialization boundary—fix it by locating the consumer that needs a collection and wrapping there, not by reverting the whole pipeline.
Stop condition: if the conversion touches a public package API used by code you can't inspect, or if you're changing code that manages files, sockets, or database transactions where a deferred close could leak a resource, pause and treat it as a designed API change with a review, not an opportunistic refactor.
Generator Patterns That Cover Most Conversions
Three generator idioms handle a large majority of eager-to-lazy rewrites.
Transformation and filtering. The list comprehension becomes a generator expression. [x.upper() for x in words if x] becomes (x.upper() for x in words if x). If you need the generator more than once, define it as a generator function so you get a fresh one per call.
Incremental accumulation. Eager code often builds a list across a loop:
Refactor to def squares_to(n): return (i * i for i in range(n)), or a bare yield loop if the body has multiple statements. The generator produces values on demand and uses constant extra memory.
Chunking a large stream. itertools.islice(iterator, size) pulls fixed batches from an iterator without consuming the rest. Combine it with a loop to process large input in bounded chunks, which is the standard pattern for files and network streams. Note the fast path: islice does not consume the next element until you ask for it, so partial consumption is safe.
Chaining and flattening. itertools.chain.from_iterable(list_of_lists) lazily concatenates. itertools.tee duplicates an iterator into two independent ones, but it buffers everything one side consumes, so it can silently defeat the memory savings; use it only when the two consumers move roughly in lockstep.
Grouping. itertools.groupby returns iterators keyed by a grouped value, but it requires input sorted by the same key and each group iterator is invalidated once you advance past it. That's a one-pass contract; document it or choose a materializing alternative when callers need random access.
Lazy Object State: Properties, Memoization, and Callables
Not all laziness is about iterators. Some is about deferring attribute computation until it's read.
property runs its getter on every read, so it defers computation without caching. Good for values that are cheap to recompute or must reflect current state. Bad for expensive work called in a loop.
functools.cached_property computes once on first access and stores the result on the instance. Good for expensive, deterministic, instance-scoped values. Caveat: it stores on the instance, which means an instance with a slots definition needs a dict entry, and deleting it from an object with a shared slots layout requires care. It also won't reflect changes to the inputs after the first read.
functools.lru_cache on a module-level function is a lazy memo cache shared across calls. It's ideal for pure functions with repeated arguments. Size the cache deliberately: an unbounded cache on a flood of distinct keys is a memory leak wearing a productivity disguise.
Callables and closures are a powerful but underused lazy primitive. If a function needs the possibility of computing a value rather than the value, accept a callable and invoke it inside. A module-level lambda: expensive() costs nothing until you call it. The classic pattern is "thunk": compute = lambda: expensive(); result = compute() — the thunk defers the work but also tells readers explicitly that it's deferred.
Lazy imports. Importing a module inside a function defers its module-level side effects until the function is called. This is useful for optional or heavy dependencies. It's less useful as a default style, because import machinery is fast and eager imports surface dependency errors early.
Descriptors are the most advanced lever; a custom descriptor's get can defer and cache. Most code doesn't need to hand-write descriptors—property and cached_property cover the common cases—but knowing that attributes resolve through descriptors explains why cached_property works at all.
Lazy Pipelines in Practice: Files, SQL, and APIs
Laziness really shows up at system boundaries, where eager code wastes work and memory.
File processing. open(path) then iterate the file object yields lines lazily. f.read() loads everything. For a 4-gigabyte log, eager reading needs several gigabytes of RAM; line iteration needs a buffer. Close the file with with so the resource closes even if the consumer stops early. If you wrap lines in a generator and return it from a function, the with block usually can't close until the consumer finishes; either keep the file handling inside the generator or document that the caller owns the lifecycle.
Database queries. Many ORMs return lazy result sets: constructing the query is cheap, and iteration hits the database. Materializing the whole result (e.g., calling list(query)) can be costly for large tables and can behave differently inside and outside transactions. Verify your ORM's query-execution point—often .all(), .first(), or list()—and what count() really does, because a lazy count may still trigger a database round trip. This is exactly where a "lazy" claim can be misleading: the evaluation is deferred, not eliminated.
HTTP/API pagination. Fetching page N+1 only after the consumer exhausts page N is a lazy-friendly pattern. Write it as a generator that fetches inside the loop:
This keeps memory bounded by one page and starts the next request only when needed. Note that partial consumption means the final page may never be requested—sometimes that's a feature, sometimes a missed data dependency. Check whether "we asked for everything" matters to your downstream logic.
Chained computation. A pipeline of generators processes one item at a time end to end. As a worked estimate, consider a pipeline that parses, transforms, and filters 1,000,000 rows. Eagerly, each stage builds a list: roughly 1,000,000 rows × (one list slot plus an object reference) per stage. Lazily, the pipeline holds at most one row in flight between stages, so the extra memory is a few references, not three million. The arithmetic isn't a benchmark; it's the shape of the difference. Actual speedups vary and may go either way, because generators add per-item overhead while eager batching helps the CPU.
Trade-Offs, Cost Model, and When Eager Wins
A fair comparison has to use equivalent criteria, so compare the two styles on the same job with the same input and the same success condition.
| Dimension | Eager (list-building) | Lazy (generator/iterator) |
|---|---|---|
| Memory for a large result | Proportional to result size | Bounded by pipeline depth |
| Time to first result | After full computation | After first item |
| Multi-pass access | Natural (len, index, loop) | Requires materialization |
| Error timing | Raised during construction | Raised during consumption |
| Debuggability | Inspect final value | Inspect item by item |
| Early exit | Work already done | Work skipped |
| Overhead per item | Lower | Higher |
| Reuse of result | Free | Exhausted after one pass |
The costs of laziness are real. Each item pays generator frame overhead, so lazy pipelines can be slower than a tight eager loop. A generator closes over its arguments, which can extend lifetimes and keep memory alive longer than expected. Exhaustion is a silent bug: iterating a generator twice yields nothing the second time, and that emptiness propagates downstream as "no results."
Eager wins when the result is small, will be traversed many times, and is needed immediately. It also wins in hot loops where per-item generator overhead dominates, and in code where surfacing malformed input early matters. A useful rule of thumb: eager at the boundaries where correctness and inspectability matter, lazy inside the long pipeline in between.
There's a testable edge case: sum(range(10**8)) is lazy in construction (the range object) but the sum itself is eager and O(n). "Lazy" describes the range, not the sum. When you claim a change is lazy, name what deferred—construction, iteration, or evaluation of the result.
Failure Modes, Debugging, and Checks
Troubleshooting is easier if you separate symptom from likely cause.
Symptom: results vanish on a second loop. Cause: a generator was iterated once and re-iterated. Check: does anything name a generator and use it in two separate for loops or comprehensions? Fix by materializing once or by making the predecessor a function that returns a fresh generator.
Symptom: len() or fails on a result. Cause: a consumer needs a sequence, not an iterator. Fix: materialize at that consumer. Consider whether the public function's contract is the wrong shape.
Symptom: errors raised at the wrong layer. Cause: lazy exceptions surface when consumed, so a try/except around construction misses them. Fix: decide where errors should be handled, and either consume inside the guarded block or raise eagerly at construction from a validation step.
Symptom: memory doesn't drop as expected. Cause: the lazy step still buffers—list() somewhere upstream, tee, unbounded lru_cache, or an ORM materializing behind the scenes. Fix: find the materialization point by tracking sizes, not assumptions.
Symptom: a file handle or database cursor leaks. Cause: a generator wraps an open resource and is never exhausted, so cleanup never runs. Fix: keep resource ownership in a with block around the consumer, or make the resource lifecycle part of the generator's contract.
Reversible check first: before changing code, run the same input through the eager path and print each intermediate collection's type and length. If any intermediate is already materialized, you know exactly where to cut. Then apply the change and re-run.
Stop condition: if the pipeline manages external transactions or file handles and partial consumption would leave a resource open or a transaction unfinished, escalate to whoever owns that subsystem's lifecycle design rather than patching it locally.
Quick Version and Region Notes
The core tools are stable across Python 3.7 and later, so the recipe above applies broadly. Two differences matter. First, functools.cached_property became part of the standard library in Python 3.8; on Python 3.7 you'd use a manual memoization pattern or a third-party descriptor. Second, itertools behavior (islice, chain, groupby, tee) has been stable for many years, so version differences there are negligible. If you're on Python 3.12 or later, the same patterns hold; changes in the language since then don't alter whether a generator defers or how cached_property caches.
On the ORM side, deferral models differ by library and version, and often by whether you're inside a transaction. Because those are version-specific, verify query execution in your own code by logging or profiling the query rather than trusting a blog post's summary. The general principle—construction ≠ execution, and materialization is the trigger—travels better than any specific library claim.
Questions the Workflow Doesn't Cover
Can I make a lazy attribute that doesn't cache? Yes—a plain property. It recomputes on every read, which is lazy in the sense of deferring to access time, not in the sense of avoiding repeat work. Choose cached_property only when the value is expensive and stable.
Is itertools always lazier than a list comprehension? Function-for-function, yes for the iterator-returning functions, but not universally: itertools.tee buffers, and groupby requires sorted input. The function's documentation tells you what it buffers; read it before assuming.
When should I just keep the eager version? When the result is small, accessed multiple times, needed immediately, and the eager code is measurably fast enough. Laziness that saves 3 KB of memory while costing readability is a net loss. Make the conversion where measurement says it matters.