Agentic AI

Generators

A generator function hands out values one at a time with yield, pausing between them. It is the short way to write an iterator, and the pattern behind streamed model replies.

Concept + code Python 3.12

A function with yield in its body is a generator function. Calling it doesn't run the body: it returns a generator, an iterator (lesson 2.6) that runs the body bit by bit, each time you ask for the next value. Nothing like it exists in Java; the closest are a hand-written Iterator class or a lazy Stream.

yield

Notebook cellPython
def square(n):
    for i in range(n):
        yield i ** 2


square(3)
OutputReal output · the address differs on each run
<generator object square at 0x0000015F14D8D080>
Notebook cellPython
for i in square(3):
    print(i)
OutputReal output
0
1
4

Pause and resume

Notebook cellPython
gen = square(3)
print(next(gen))
print(next(gen))
print(next(gen))
next(gen)
OutputReal output · last line of the error
0
1
4
StopIteration

Calling square(3) ran none of its body. Each next() runs the body until the next yield, hands out that value and pauses right there, keeping n and i. The next call resumes after the yield. When the body ends, next() raises StopIteration, like any iterator at its end.

A generator pauses at yield

Press Play or step with Next. The caller is on the left; the generator, where it stopped and what it remembers, on the right.

Step0 / 5of the run
Generator-new, paused or done
i-kept between calls
Handed out-values so far
The caller and the generator On the left, the caller's current call and what it gets back. On the right, the generator object with the function's three lines, a marker on the line where it paused, and its local variables n and i. caller - gets back - call value gen generator object - def square(n): for i in range(n): yield i ** 2 paused here local variables n = 3 i = -

Ready

Notebook cell· highlighted lines run at this stepPython
def square(n):
    for i in range(n):
        yield i ** 2

gen = square(3)
print(next(gen))
print(next(gen))
print(next(gen))
next(gen)

Observe: the list [0, 1, 4] is never built. One value exists at a time, which is why a generator can stream data of any length.

It continues where it stopped

Notebook cellPython
def my_generator():
    yield 1
    yield 2
    yield 3


gen = my_generator()
print("next:", next(gen))
for val in gen:
    print("loop:", val)
OutputReal output
next: 1
loop: 2
loop: 3

The loop picks up after the value next() already took. A generator makes one pass; once it has finished, it stays empty.

The countdown, as a generator

Notebook cellPython
def countdown(start):
    while start > 0:
        yield start
        start -= 1


print(list(countdown(3)))
OutputReal output
[3, 2, 1]

Compare the Countdown class in lesson 2.6: Python writes __iter__ and __next__ for you, and the state lives in ordinary local variables.

Generator expressions

Notebook cellPython
squares = (x * x for x in range(5))
print(squares)
print(sum(squares))
OutputReal output · the address differs on each run
<generator object <genexpr> at 0x0000015F14D8C520>
30

Round brackets instead of square ones make a generator instead of a list (lesson 1.8): sum() pulls the squares one at a time and no list is ever built. That is the point of generators: one item in memory at a time, however long the sequence.

A chat model's stream() method works the same way from the outside: for chunk in model.stream(...) hands you the reply piece by piece as it arrives (lesson 9.1).

Practice

The task reads this file; create it next to your notebook:

large_file.txt
2026-01-05 09:00 INFO  Service started
2026-01-05 09:01 INFO  Loaded 120 documents
2026-01-05 09:02 WARN  Slow response from the search tool
2026-01-05 09:03 INFO  Answered 3 questions
2026-01-05 09:04 INFO  Service stopped
Practice 1Read a large file lazily. Write a generator read_large_file(file_path) that yields a file's lines one at a time, and use it to print the lines of large_file.txt without their line breaks.Show solution
Notebook cellPython
def read_large_file(file_path):
    with open(file_path, "r") as file:
        for line in file:
            yield line


for line in read_large_file("large_file.txt"):
    print(line.strip())
OutputReal output
2026-01-05 09:00 INFO  Service started
2026-01-05 09:01 INFO  Loaded 120 documents
2026-01-05 09:02 WARN  Slow response from the search tool
2026-01-05 09:03 INFO  Answered 3 questions
2026-01-05 09:04 INFO  Service stopped

A file object already reads one line at a time (lesson 1.17); the generator wraps it so filtering or parsing can live in one place, and memory stays flat whether the file has five lines or five million. The file closes when the generator finishes.