Two short keywords do a lot of work in Python. with makes sure a resource is closed, whatever happens. yield lets a function hand back values one at a time, pausing in between. You’ll find both in file handling, database code, HTTP clients and, above all, in streaming: every chat app that shows an LLM’s answer word by word is built on them.
The good news: one of them has a true Java twin, and the other replaces a class you’ve written many times.
This is part 11 of Python for Java Developers. Part 10 covered decorators.
with is try-with-resources
try (BufferedReader r = Files.newBufferedReader(path)) {
String text = r.lines().collect(Collectors.joining("\n"));
}
// r is closed here, even after an exceptionwith open("notes.txt", encoding="utf-8") as f:
text = f.read()
# f is closed here, even after an exceptionwith X as name: gives you the resource as name. When the indented block ends, normally or through an exception, it’s cleaned up. The objects that support with are called context managers, Python’s AutoCloseable.
Files, the everyday case
# read everything
with open("prompt.txt", encoding="utf-8") as f:
prompt = f.read()
# read line by line: the file object is itself iterable
with open("data.jsonl", encoding="utf-8") as f:
for line in f:
record = json.loads(line)
# write: "w" replaces the file, "a" appends
with open("answer.md", "w", encoding="utf-8") as f:
f.write(answer)
Always pass encoding="utf-8". Without it, Python uses the platform’s default, which on Windows can break on the curly quotes and emoji that model output is full of.
For small files, pathlib is shorter and handles the closing for you:
from pathlib import Path
text = Path("notes.txt").read_text(encoding="utf-8")
Path("out.txt").write_text(answer, encoding="utf-8")
for p in Path("docs").glob("*.md"):
print(p.name)
Path is Java’s java.nio.file.Path and Files in one object.
Not only files
Anything with a setup and a teardown can be a context manager. Several can share one with, like multiple resources in one Java try (...):
with open("in.txt", encoding="utf-8") as src, open("out.txt", "w", encoding="utf-8") as dst:
dst.write(src.read().upper())
You’ll see with around database connections and transactions, HTTP clients, locks (with lock: is Java’s synchronized block), temporary folders, and streaming API responses.
Writing your own context manager
Java needs a class implementing AutoCloseable. Python can do it with one function and a decorator from the standard library:
import time
from contextlib import contextmanager
@contextmanager
def timed(label):
start = time.perf_counter()
try:
yield # the with block runs here
finally:
print(f"{label}: {time.perf_counter() - start:.2f}s")
with timed("embedding"):
vectors = embed_all(chunks)
# prints "embedding: 3.41s"
Everything before yield is the setup; everything after it is the cleanup. The yield is where the body of the with runs. That’s your first look at yield, and it’s the key to the rest of this article.
yield turns a function into a generator
A function that contains yield becomes a generator. Instead of returning one value and ending, it hands back values one at a time and pauses between them.
class Chunks implements Iterator<String> {
private final String text; private final int size; private int pos = 0;
Chunks(String text, int size) { this.text = text; this.size = size; }
public boolean hasNext() { return pos < text.length(); }
public String next() {
String s = text.substring(pos, Math.min(pos + size, text.length()));
pos += size;
return s;
}
}def chunks(text, size):
for i in range(0, len(text), size):
yield text[i:i + size]Both are used with a plain loop:
for piece in chunks(book, 1000):
embed(piece)
The Python version keeps its state (i) in the paused function, so there’s no class, no hasNext, no next. Write the loop you’d write to build a list, and put yield where you’d call append.
How a generator runs
- Calling
chunks(book, 1000)runs nothing. It returns a generator object. - The
forloop asks for the next value. The function runs until it reachesyield, hands over the value, and pauses. - The next request resumes right after the
yield, with all local variables intact. - When the function ends, the loop ends.
Compare that with building a list first:
def chunks_list(text, size):
return [text[i:i + size] for i in range(0, len(text), size)]
The list version holds every chunk in memory at once and does all the work before you see the first chunk. The generator holds one chunk at a time and gives you the first one immediately. For a 2 GB log file, that’s the difference between working and running out of memory.
Generators in practice
Reading huge files. A file object already yields lines lazily, so you can chain generators into a pipeline that never loads the whole file:
def records(path):
with open(path, encoding="utf-8") as f:
for line in f:
if line.strip():
yield json.loads(line)
errors = (r for r in records("app.jsonl") if r["level"] == "ERROR")
for err in errors:
alert(err)
The middle line is a generator expression (from the comprehensions part): round brackets make it lazy. It’s a Java stream pipeline, built from plain functions.
Paging through an API. Hide the paging inside a generator and callers just loop:
def all_issues(client):
page = 1
while True:
batch = client.list_issues(page=page)
if not batch:
return # ends the generator
yield from batch # yield every item of the batch
page += 1
yield from batch yields each item of batch in turn.
Streaming LLM answers
Users want to see an answer appear word by word instead of waiting twenty seconds. In Python, streaming is with and a generator working together. The SDK’s stream is a context manager (so the connection is always closed) that exposes a generator of text pieces:
def stream_answer(question):
with client.messages.stream(
model=MODEL,
max_tokens=800,
messages=[{"role": "user", "content": question}],
) as stream:
for text in stream.text_stream:
yield text
for piece in stream_answer("Explain embeddings simply"):
print(piece, end="", flush=True)
stream_answer wraps the SDK’s generator and passes each piece along. A web framework can send the same generator straight to the browser:
from fastapi.responses import StreamingResponse
@app.get("/ask")
def ask(q: str):
return StreamingResponse(stream_answer(q), media_type="text/plain")
Traps for Java developers
- A generator runs only once. After one loop it’s empty, and a second loop silently does nothing. If you need the values twice, store them:
items = list(gen). - Nothing happens until you loop. Calling a generator function doesn’t run any of its code. If it has side effects (writing files, calling APIs), they happen only as you consume it.
- Using a resource after the
with. The file or stream is already closed; reading it raises an error. - Forgetting
encoding="utf-8". It works on your Mac and breaks on a Windows server.
Key takeaways
withis try-with-resources: the resource is closed when the block ends, even on errors.- Open text files with
encoding="utf-8", or usepathlib.Path.read_text. @contextmanagerturns a function with oneyieldinto a context manager: setup before, cleanup after.- A function with
yieldis a generator: a lazy iterator without the class. - Generators keep memory flat and deliver the first value at once, which is what streaming needs.
- A generator can be consumed only once.
Frequently asked questions
What is the with statement in Python?
It runs a block of code inside a context manager, which sets something up before the block and cleans it up afterwards, even if an exception is raised. It’s Python’s equivalent of Java’s try-with-resources.
What does yield do in Python?
It makes a function a generator. Each yield hands one value to the caller and pauses the function; the next request resumes it right after the yield. The function produces a sequence of values lazily instead of returning a list.
What is the difference between a generator and a list in Python?
A list holds all its values in memory and can be looped over many times. A generator produces values one at a time when asked, uses almost no memory, and can be looped over only once.
How do I read a large file line by line in Python?
Open it with with open(path, encoding="utf-8") as f: and loop for line in f:. The file object reads lazily, so only one line is in memory at a time.
How do I write my own context manager?
Either write a class with __enter__ and __exit__ methods, or, more simply, decorate a generator function with @contextlib.contextmanager: code before yield is the setup, code after it (ideally in finally) is the cleanup.
Next in the series: Python async and await vs CompletableFuture, and how one thread waits on many LLM calls at once.
Comments