Generators, Iterators & Context Managers
Every for loop since Chapter 4 has quietly relied on something never fully explained: how does for item in some_list: actually pull one value out at a time? And every with open(...) as f: since Chapter 13 has relied on something else never fully explained: how does Python guarantee the file gets closed, even if the code inside the block crashes? This chapter opens up both black boxes — and along the way introduces yield, a tool for writing functions that hand back one value at a time instead of building a whole result up front, which is exactly how real systems process files and data streams too large to fit in memory at once.
How to read this chapter
- The first three sub-topics are one throughline: what an iterator actually is, how
yieldlets a function build one lazily, and why a generator expression is the same idea in one line. - The last three sub-topics are a second throughline: the
withstatement's real protocol, writing a custom class that plugs into it, and why both throughlines converge on the same production use case — streaming data too big to hold in memory all at once. - Everything from Chapters 1-16 still applies — classes, dunder methods,
@property, inheritance, all of it.yield, generator expressions, and the__enter__/__exit__protocol are the new ingredients.
.readlines() would try to hold 40 GB in memory at once — on most machines, that crashes before a single line gets processed. Yet for line in file: has worked fine on tiny files since Chapter 13, without ever explaining how. This chapter's answer is the same idea in both cases: process one line at a time, and never hold more than one line in memory at once. That idea has a name — lazy evaluation — and generators are how Python code writes it directly.
1. Iterables vs. iterators
- An iterable is anything that can be looped over — it has an
__iter__method. - An iterator is the object that actually does the looping — it has a
__next__method, and raisesStopIterationonce exhausted. - A
forloop is just syntax sugar: it calls__iter__once, then__next__repeatedly, untilStopIterationstops it.
for loops — the same mechanism this whole chapter builds on.
A list is iterable, but the object that does the actual counting
is something different, produced by calling iter()
on it:
for loop. Lists,
tuples, strings, dicts, and open files are all iterables. Under
the hood, an iterable defines an __iter__ method.
numbers = [10, 20, 30]
iterator = iter(numbers)
print(iterator)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
<list_iterator object at 0x74f5a81e0640>
10
20
30
Traceback (most recent call last):
File "iter_and_next_demo.py", line 7, in <module>
print(next(iterator))
StopIteration
__next__, which
returns the next value each time it's called, and raises
StopIteration once there's nothing left. Calling
iter() on an iterable produces one.
iter(numbers) hands back a list_iterator
object, completely separate from the list itself. Each call to
next(iterator) moves it forward by one value. The
fourth call has nothing left to return, so it raises
StopIteration — that error is deliberate output
above, not a bug, since a real for loop is written to
catch it automatically and stop cleanly instead of crashing.
A for loop never calls next() by
hand — it does exactly that work behind the scenes:
numbers = [10, 20, 30]
iterator = iter(numbers)
while True:
try:
value = next(iterator)
except StopIteration:
break
print(value)
10
20
30
This while True loop is exactly what
for value in numbers: print(value) already does
automatically — call iter() once to get an
iterator, then call next() in a loop, catching
StopIteration to know when to stop. Every
for loop written since Chapter 4 has been this
pattern, hidden behind convenient syntax.
A class can become its own iterator by defining both
__iter__ (returning self) and
__next__:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for number in Countdown(3):
print(number)
3
2
1
Countdown(3) is both the iterable (it has
__iter__) and its own iterator (it has
__next__). Each call to __next__
returns self.current, then decrements it; once
self.current reaches 0, it raises
StopIteration, and the for loop stops
cleanly, exactly like it does for a list.
Go Deeper: writing a working iterator class by hand is rare
Countdown above is deliberately the "long way" to
show the mechanism. Sub-topic 2 introduces yield,
which lets Python build an equivalent iterator automatically
from a much shorter function — almost no real code writes
__iter__/__next__ by hand once
generator functions are available.
- An iterable has
__iter__; an iterator has__next__and raisesStopIterationwhen exhausted. - A
forloop callsiter()once, thennext()repeatedly, stopping onStopIteration. - A class can be its own iterator by defining both
__iter__(returningself) and__next__.
2. Generator functions and yield
- A function containing
yieldanywhere in its body becomes a generator function — calling it returns a generator object instead of running the body immediately. yieldpauses the function and hands back one value; the next call tonext()resumes right where it left off, with all local variables intact.return(with no value) inside a generator function simply ends it early, raisingStopIteration, the same as running off the end of the body.
Countdown class needed a whole class with two dunder methods just to be an iterator. A generator function gets the exact same behavior from a few lines using yield.
The same countdown behavior, written as a generator function instead of a class:
yield at least once. Calling it doesn't run
the body — it immediately returns a generator object,
an iterator that runs the body only as next() is
called on it, one yield at a time.
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(gen)
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
<generator object countdown at 0x7cff9b346140>
3
2
1
Traceback (most recent call last):
File "countdown_generator_demo.py", line 11, in <module>
print(next(gen))
StopIteration
countdown(3) doesn't print anything or run the
while loop yet — it returns a generator object.
Each next(gen) call runs the body only until the
next yield n, hands back that value, and then
pauses — n, and every other local
variable, stay exactly as they were, ready to pick back up on the
following next() call. When n finally
reaches 0, the while condition fails,
the function body ends, and StopIteration is raised
automatically — no raise StopIteration ever needed
by hand, unlike Sub-topic 1's class version.
A normal for loop drives a generator exactly like
any other iterator, calling next() until it's
exhausted:
def countdown(n):
print("Starting countdown")
while n > 0:
yield n
n -= 1
print("Liftoff!")
for number in countdown(3):
print(number)
Starting countdown
3
2
1
Liftoff!
Notice "Starting countdown" only prints once the
for loop actually starts pulling values, not when
countdown(3) is first called — proof the function
body genuinely hasn't run yet at that point. "Liftoff!"
prints only after the last yield, right before the
generator raises StopIteration and the loop ends.
yield vs. return?
return ends a function permanently and hands back
one final value. yield hands back one value but
pauses the function instead of ending it — the
next call to next() resumes right after that
yield, with every local variable exactly as it was.
Go Deeper: a generator can only be looped over once
Once a generator object is fully exhausted (or even partially
consumed), there's no way to "rewind" it — calling
countdown(3) again creates a brand-new generator
instead. This is different from a list, which can be looped
over as many times as needed. It's a direct consequence of a
generator not storing its values anywhere — each one is
produced once, on demand, and then gone.
- A function with
yieldanywhere in it is a generator function — calling it returns a generator object without running the body. yieldpauses the function and hands back a value; the nextnext()call resumes right after it, state intact.- Running off the end of the body (or an explicit bare
return) ends the generator, raisingStopIteration.
3. Generator expressions
- A generator expression looks like a list comprehension but with parentheses instead of square brackets:
(x for x in ...). - A list comprehension builds the entire list in memory immediately; a generator expression produces values lazily, one at a time, only as they're requested.
- For large or unbounded sequences, a generator expression can use a tiny, constant amount of memory where a list comprehension would need memory proportional to the whole sequence.
def with yield to get lazy, one-at-a-time values. A generator expression gets the same laziness in a single line, for the common case of transforming or filtering an existing sequence.
The syntax difference between a list comprehension and a generator expression is exactly one pair of brackets:
(expression for item in iterable) —
but with parentheses instead of square brackets. It produces a
generator object, evaluating one item at a time only as
requested, instead of building a full list immediately.
numbers = [1, 2, 3, 4, 5]
squares_list = [n ** 2 for n in numbers]
squares_gen = (n ** 2 for n in numbers)
print(squares_list)
print(squares_gen)
print(list(squares_gen))
[1, 4, 9, 16, 25]
<generator object <genexpr> at 0x786fd5ece810>
[1, 4, 9, 16, 25]
squares_list already contains all five squared
values the moment it's created. squares_gen instead
prints as a generator object — none of the squaring has actually
happened yet — until something consumes it, like wrapping it in
list(...), which pulls every value out one at a
time and confirms they match.
The real reason to reach for a generator expression is memory, not syntax. Comparing the two side by side on a million-item range makes the difference concrete:
import sys
squares_list = [x ** 2 for x in range(1_000_000)]
squares_gen = (x ** 2 for x in range(1_000_000))
print(sys.getsizeof(squares_list))
print(sys.getsizeof(squares_gen))
8448728
208
squares_list takes roughly 8.4 million bytes,
because Python already computed and stored all one million
squared values. squares_gen takes 208 bytes —
barely more than an empty generator — because it hasn't
computed a single value yet; it only knows how to
produce the next one when asked. That gap only grows as the
sequence grows, which is exactly why a generator expression can
handle a sequence too large to fit in memory as a list at all.
A generator expression can also be passed directly into a
function like sum() without the outer parentheses
needing to be doubled up:
total = sum(n ** 2 for n in range(1, 6))
print(total)
55
sum() never needs the full list of squares sitting
in memory at once — it just keeps asking the generator
expression for one more value and adding it to a running total,
which is the whole point: the values are consumed and discarded
one at a time, never all held at once.
Go Deeper: a generator expression is a one-time-use view
Just like a generator function's result (Sub-topic 2), a
generator expression can only be consumed once — after
list(squares_gen) runs, calling
list(squares_gen) a second time returns an empty
list, since every value has already been produced and there's
nothing left to give. A fresh generator expression has to be
created again for a second pass.
(x for x in ...)is a generator expression — same shape as a list comprehension, parentheses instead of brackets.- A list comprehension builds the whole list in memory immediately; a generator expression produces one value at a time, lazily.
- For large or unbounded sequences, that laziness keeps memory use small and roughly constant, instead of growing with the sequence.
4. The with statement, generalized
with open(...) as f:, used since Chapter 13, is one example of a much more general pattern called the context manager protocol.- Any object with
__enter__and__exit__methods can be used afterwith— not just files. __exit__is guaranteed to run when the block ends, even if an exception was raised inside it — that guarantee is the entire reasonwithexists.
with open(...) as f: has looked like special file syntax since Chapter 13. It's actually just the most common use of a general protocol any class can plug into — Sub-topic 5 writes one from scratch.
A file opened with with is confirmed closed the
moment the block ends, without ever calling
f.close() directly:
__enter__ and __exit__, that a
class defines so its objects can be used after with.
__enter__ runs at the start of the block;
__exit__ runs at the end — always, even if the block
raised an exception.
with open("sample.txt", "w") as f:
f.write("hello\nworld\n")
with open("sample.txt", "r") as f:
contents = f.read()
print(contents)
print(f.closed)
hello
world
True
f.closed is True right after the
with block ends, even though nothing called
f.close() anywhere in the code. Behind the scenes,
open(...) returns a file object with its own
__enter__ (which just returns the file itself,
bound to f) and __exit__ (which calls
close()) — with is what calls both of
those automatically.
The guarantee that matters most is what happens when the code inside the block raises an exception partway through:
try:
with open("sample.txt", "r") as f:
print(f.closed)
raise ValueError("something went wrong inside the block")
except ValueError as e:
print(f"Caught: {e}")
print(f.closed)
False
Caught: something went wrong inside the block
True
f.closed is True at the very end, even
though a ValueError was raised in the middle of the
block, before reaching any explicit close. __exit__
still ran and closed the file first, and only then did the
exception continue propagating outward to the except
clause. Without with, a crash between
open() and a manual f.close() call
would leave the file handle open indefinitely — exactly the bug
with exists to make impossible.
Go Deeper: what __exit__'s three parameters are for
__exit__(self, exc_type, exc_value, traceback)
receives details about any exception that happened inside the
block — all three are None if nothing went wrong.
Sub-topic 5 uses this to detect whether an exception occurred
and decide what to do about it.
with obj as name:works for any object defining__enter__and__exit__, not just files.__enter__runs at the start of the block;__exit__runs at the end, unconditionally.__exit__still runs even if the block raises an exception — that guaranteed cleanup is the entire reasonwithexists.
5. Writing a custom context manager
- Any class can become a context manager by defining
__enter__(self)and__exit__(self, exc_type, exc_value, traceback). __enter__'s return value is what gets bound to theasvariable in thewithstatement.__exit__returningFalse(or nothing) lets any exception continue propagating; returningTruewould silently swallow it — almost always the wrong choice.
A Timer context manager records how long the code
inside its block took to run, with no risk of forgetting to
stop the clock:
__enter__ / __exit__?
__enter__(self) runs when a with block
starts, and its return value becomes the as
variable. __exit__(self, exc_type, exc_value, traceback)
runs when the block ends, whether it finished normally or an
exception interrupted it.
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.end = time.perf_counter()
self.elapsed = self.end - self.start
return False
with Timer() as t:
total = sum(range(1_000_000))
print(f"Sum: {total}")
print(f"Took under a second: {t.elapsed < 1}")
Sum: 499999500000
Took under a second: True
with Timer() as t: calls __enter__,
which records the start time and returns self —
that's why t ends up bound to the whole
Timer object, giving access to t.elapsed
afterward. The instant the block ends, __exit__
runs automatically, recording the end time and computing
self.elapsed — there's no way to forget to stop the
clock, because that responsibility isn't left to whoever writes
the with block.
A context manager can also wrap a resource that genuinely needs cleanup, like a file, and react to whether an exception happened:
class ManagedFile:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
if exc_type is not None:
print(f"An exception occurred: {exc_value}")
return False
with ManagedFile("sample.txt", "r") as f:
print(f.read())
hello
world
ManagedFile's __enter__ opens the file
and returns it — so f is the actual file object,
not the ManagedFile instance. Its
__exit__ always closes the file first, then checks
exc_type: if it's None, nothing went
wrong; if it isn't, something raised inside the block, and this
version logs it before returning False, which lets
that exception keep propagating instead of hiding it.
Go Deeper: returning True from __exit__ swallows the exception
If __exit__ returns True, Python
treats the exception as handled and stops it from propagating
any further — the code after the with block just
continues as if nothing happened. That's occasionally useful
for a context manager designed specifically to suppress one
known error type, but doing it by accident hides real bugs.
Returning False (or nothing, which Python treats
as False) is the safe default.
- Any class becomes a context manager by defining
__enter__and__exit__. __enter__'s return value becomes thewith ... as name:variable.__exit__should returnFalse(or nothing) so exceptions keep propagating instead of being silently swallowed.
6. Real-world streaming with generators & context managers
- A generator function combined with
with open(...) as f:can stream a huge file line-by-line, never holding more than one line in memory. - This exact pattern — generator plus context manager — is how many real data pipelines read logs, CSVs, and datasets far larger than available RAM.
- The caller of a streaming generator writes an ordinary
forloop, with no idea (or need to know) that lazy evaluation is happening underneath.
This chapter's opening hook described a 40 GB log file that
can't be loaded all at once. Here's the actual pattern that
solves it, combining Sub-topic 2's yield with
Sub-topic 4's with:
def read_large_file(filename):
with open(filename, "r") as f:
for line in f:
yield line.strip()
with open("big.txt", "w") as f:
for i in range(5):
f.write(f"log line {i}\n")
for line in read_large_file("big.txt"):
print(line)
log line 0
log line 1
log line 2
log line 3
log line 4
read_large_file is a generator function that opens
the file with with (so it's always closed, even if
something downstream raises an exception) and yields
one stripped line at a time. Whether the file has 5 lines or 5
billion lines, this function never holds more than one line in
memory — the for line in f: loop itself is already
lazy, since a file object is an iterator too, exactly like Sub-topic
1 described.
The calling code — for line in read_large_file("big.txt"): print(line)
— looks identical whether it's reading 5 lines or streaming
gigabytes; nothing about the calling loop changes based on file
size. That's the real payoff: the caller writes ordinary,
simple code, and the generator function is entirely responsible
for staying memory-efficient underneath it.
- Log-processing pipelines read multi-gigabyte server logs one line at a time with a generator, filtering for errors without ever loading the full file into memory.
- Data engineering tools (like pandas' chunked readers) use the exact same generator pattern to process CSV files far larger than available RAM, one chunk at a time.
- Database libraries wrap connections and transactions in context managers so a crash mid-query still guarantees the connection is closed or the transaction is rolled back.
Go Deeper: what's still missing after this chapter?
The standard library's contextlib module offers a
shortcut for turning an ordinary generator function into a
context manager, and Python's itertools module
adds many more lazy building blocks on top of what's covered
here. Both build directly on the ideas in this chapter and are
worth exploring once these fundamentals feel solid.
- A generator function opening a file with
withcan stream it line-by-line, using memory proportional to one line, not the whole file. - This generator-plus-context-manager pattern is exactly how real log, CSV, and data pipelines handle files larger than RAM.
- The calling code stays a plain
forloop, unaware of and unaffected by the laziness happening underneath.
- Data pipelines and ETL tools lean on generators constantly to process files, database result sets, and API responses too large to fit entirely in memory.
- Context managers show up anywhere a resource needs guaranteed cleanup — files, database connections, network sockets, locks — not just the file-handling introduced back in Chapter 13.
- Interviewers frequently ask "how would you process a file too big to fit in memory?" specifically to check for this chapter's generator-based streaming pattern.
Points to Remember
- An iterable has
__iter__; an iterator has__next__and raisesStopIterationwhen exhausted — aforloop is just this mechanism wrapped in convenient syntax. - A function containing
yieldbecomes a generator function: calling it returns a generator object, and eachyieldpauses execution, preserving local state until the nextnext()call. - A generator expression,
(x for x in ...), produces values lazily one at a time, unlike a list comprehension, which builds the entire list in memory immediately — the difference matters most on large or unbounded sequences. withworks with any object defining__enter__/__exit__, and guarantees__exit__runs even if the block raises an exception.- Any class can become a custom context manager by implementing
__enter__and__exit__— useful for far more than files, like timing code or managing any resource that needs guaranteed cleanup. - Combining a generator function with
with open(...) as f:is the standard real-world pattern for streaming huge files line-by-line without ever loading the whole thing into memory.