🐍 Python for Everyone

← Back to all chapters

Chapter 17 of 27 Intermediate 70 min read

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

Picture a log-processing service that needs to scan a 40 GB server log file for error lines. Loading the whole file into a list with .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.
Sub-topic 1 of 6

1. Iterables vs. iterators

At a glance
  • 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 raises StopIteration once exhausted.
  • A for loop is just syntax sugar: it calls __iter__ once, then __next__ repeatedly, until StopIteration stops it.
Why this matters: lists, strings, dicts, and files have all been "loopable" since early chapters. This sub-topic finally explains the mechanism underneath every one of those 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:

What is... an iterable? An iterable is any object that can produce an iterator — anything usable in a for loop. Lists, tuples, strings, dicts, and open files are all iterables. Under the hood, an iterable defines an __iter__ method.
iter_and_next_demo.py
numbers = [10, 20, 30]
iterator = iter(numbers)
print(iterator)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
actual output of iter_and_next_demo.py
<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
What is... an iterator? An iterator is the object that actually tracks position while looping — it defines __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:

for_loop_under_the_hood.py
numbers = [10, 20, 30]

iterator = iter(numbers)
while True:
    try:
        value = next(iterator)
    except StopIteration:
        break
    print(value)
actual output of for_loop_under_the_hood.py
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__:

custom_iterator_demo.py
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)
actual output of custom_iterator_demo.py
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.

try_it.py
Click "Run Code" — try changing Countdown(5) to a different starting number.
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.

Quick recap
  • An iterable has __iter__; an iterator has __next__ and raises StopIteration when exhausted.
  • A for loop calls iter() once, then next() repeatedly, stopping on StopIteration.
  • A class can be its own iterator by defining both __iter__ (returning self) and __next__.
Sub-topic 2 of 6

2. Generator functions and yield

At a glance
  • A function containing yield anywhere in its body becomes a generator function — calling it returns a generator object instead of running the body immediately.
  • yield pauses the function and hands back one value; the next call to next() resumes right where it left off, with all local variables intact.
  • return (with no value) inside a generator function simply ends it early, raising StopIteration, the same as running off the end of the body.
Why this matters: Sub-topic 1's 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:

What is... a generator function? A generator function is any function whose body contains 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.
countdown_generator_demo.py
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))
actual output of countdown_generator_demo.py
<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:

countdown_for_loop_demo.py
def countdown(n):
    print("Starting countdown")
    while n > 0:
        yield n
        n -= 1
    print("Liftoff!")

for number in countdown(3):
    print(number)
actual output of countdown_for_loop_demo.py
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.

What is... 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.
try_it.py
Click "Run Code" — try adding a print("done!") line after the while loop.
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.

Quick recap
  • A function with yield anywhere in it is a generator function — calling it returns a generator object without running the body.
  • yield pauses the function and hands back a value; the next next() call resumes right after it, state intact.
  • Running off the end of the body (or an explicit bare return) ends the generator, raising StopIteration.
Sub-topic 3 of 6

3. Generator expressions

At a glance
  • 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.
Why this matters: Sub-topic 2 wrote a whole 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:

What is... a generator expression? A generator expression is written like a list comprehension — (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.
genexpr_vs_list_demo.py
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))
actual output of genexpr_vs_list_demo.py
[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:

genexpr_memory_demo.py
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))
actual output of genexpr_memory_demo.py
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:

genexpr_sum_demo.py
total = sum(n ** 2 for n in range(1, 6))
print(total)
actual output of genexpr_sum_demo.py
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.

try_it.py
Click "Run Code" — try changing the condition to n % 2 != 0 for odd numbers instead.
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.

Quick recap
  • (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.
Sub-topic 4 of 6

4. The with statement, generalized

At a glance
  • 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 after with — 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 reason with exists.
Why this matters: 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:

What is... the context manager protocol? The context manager protocol is a pair of methods, __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_recap_demo.py
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)
actual output of with_recap_demo.py
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:

with_exception_safety_demo.py
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)
actual output of with_exception_safety_demo.py
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.

try_it.py
Click "Run Code" — try adding a third f.write() line before the with block ends.
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.

Quick recap
  • 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 reason with exists.
Sub-topic 5 of 6

5. Writing a custom context manager

At a glance
  • 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 the as variable in the with statement.
  • __exit__ returning False (or nothing) lets any exception continue propagating; returning True would silently swallow it — almost always the wrong choice.
Why this matters: the guaranteed-cleanup pattern Sub-topic 4 described isn't limited to files — a database connection, a network socket, or a simple timer all benefit from the exact same guarantee, and any class can opt in.

A Timer context manager records how long the code inside its block took to run, with no risk of forgetting to stop the clock:

What is... __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.
timer_context_manager_demo.py
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}")
actual output of timer_context_manager_demo.py
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:

managed_file_demo.py
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())
actual output of managed_file_demo.py
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.

try_it.py
Click "Run Code" — try changing range(100000) to a bigger or smaller number.
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.

Quick recap
  • Any class becomes a context manager by defining __enter__ and __exit__.
  • __enter__'s return value becomes the with ... as name: variable.
  • __exit__ should return False (or nothing) so exceptions keep propagating instead of being silently swallowed.
Sub-topic 6 of 6

6. Real-world streaming with generators & context managers

At a glance
  • 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 for loop, with no idea (or need to know) that lazy evaluation is happening underneath.
Pattern to remember: whenever a real pipeline needs to process "more data than fits in memory," the answer is almost always a generator — read one unit, process it, discard it, move to the next.

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:

streaming_reader_demo.py
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)
actual output of streaming_reader_demo.py
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.

Honest caution: a generator's laziness is also a limitation — its values can only be consumed once, and if random access (jumping to item #500 without reading the first 499) is genuinely needed, a generator is the wrong tool and a list is a better fit. Reach for generators specifically when data is processed once, in order, and might be too large to hold in memory all at once.
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.

Quick recap
  • A generator function opening a file with with can 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 for loop, unaware of and unaffected by the laziness happening underneath.
In the Real World

Points to Remember

← All Chapters Take the Quiz →