Sub topic 10
Explaining Code That Spans Many Files
This chapter assumes you can already write a single-file explanation prompt: a specific question, the relevant code in a delimited block, and a request for a particular kind of answer. It also assumes you can run small Python snippets and shell commands locally. Here you will apply those skills when the code you need to understand is spread across dozens of files and won't fit in one prompt.
Why many files change the problem
With one function, you can paste everything and ask. With a real project, three things get in the way.
- Size. Assistants read a limited amount of text per conversation. Pasting a whole repository either fails or buries the relevant lines among irrelevant ones.
- Missing definitions. A function calls
load_config(), which lives elsewhere. If the assistant can't see that definition, it fills the gap with a guess based on the name. - Hidden wiring. Behavior often comes from places that don't look like code: configuration files, dependency injection, decorators that register handlers, environment variables, and plugins loaded by name.
The strategy is the same in every case. Don't ask the assistant to understand the project. Ask it to explain one path through the project, and supply the files that path touches.
Some tools can search your repository themselves. A terminal or editor assistant may open files, run grep, and follow imports on its own. This helps, but the same discipline applies. You still need to say which path you care about, and you still need to check which files the tool actually read.
Build a map before you ask
Before writing a prompt, get a rough picture of how files relate. A map lets you choose which files to share, and it gives the assistant a frame to reason in.
The script below lists which modules in a Python project import which other modules in the same project, then shows the most-imported modules. Modules that many others depend on are usually core pieces worth understanding first.
import ast
import sys
from collections import Counter
from pathlib import Path
EXCLUDED = {".venv", "venv", "__pycache__", "node_modules", ".git", "build", "dist"}
def module_name(root: Path, path: Path) -> str:
parts = list(path.relative_to(root).with_suffix("").parts)
if parts[-1] == "__init__":
parts = parts[:-1]
return ".".join(parts)
def imports_of(path: Path) -> set[str]:
tree = ast.parse(path.read_text(encoding="utf-8"))
found = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
found.update(alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
found.add(node.module)
return found
def main(root_arg: str) -> None:
root = Path(root_arg).resolve()
files = [
p for p in root.rglob("*.py")
if not EXCLUDED.intersection(p.relative_to(root).parts)
]
modules = {module_name(root, p): p for p in files if module_name(root, p)}
fan_in = Counter()
for name, path in sorted(modules.items()):
try:
imports = imports_of(path)
except SyntaxError as err:
print(f"# skipped {name}: {err.msg}")
continue
internal = sorted(i for i in imports if i in modules and i != name)
for target in internal:
print(f"{name} -> {target}")
fan_in[target] += 1
print("\nMost imported modules:")
for name, count in fan_in.most_common(5):
print(f"{count:3d} {name}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else ".")Run it as python map_imports.py path/to/project. The output is a list of a -> b lines plus a ranking. It has limits. It skips relative imports such as from . import x, and it can't see dynamic imports, plugin registries, or anything wired through configuration. Treat the result as a starting sketch, not a full dependency graph.
You can paste the edge list into a prompt. It is far shorter than the source files and gives the assistant the project's shape.
Pick one path and trace it
The most reliable way to understand a large codebase is to follow a single concrete action from its entry point to its effect. Examples: "a POST to /orders creates an order," "running cli sync writes the local cache," "a message arrives on the queue and gets retried."
To pick the path, find the entry point first. In a web service it is the route definition. In a command-line tool it is the main function or the argument parser. In a library it is the public function you call. Then name the outcome you care about, such as "a row is inserted" or "an error is returned."
Write a multi-file prompt
A multi-file prompt has the parts of a single-file prompt plus two more: the map and an explicit rule about gaps. Here is a template for a request about an order service.
I'm new to a Python web service and need to understand how an order gets created. I know Flask routes. I don't know this project's layout.
Project map (internal imports only):
api.routes -> orders.service
orders.service -> orders.models
orders.service -> payments.client
orders.service -> events.publisher
Question: when a client sends POST /orders, what happens, in order, until the response is returned?
I'm including four files below, each in its own tagged block with its path. Use only these files. If the answer depends on code you haven't seen (for example, what payments.client does internally), say so and name the file you'd need rather than guessing. For each step, cite the file and function.
<file path="api/routes.py">
...
</file>
<file path="orders/service.py">
...
</file>The template does five things:
- It states what you already know, so the assistant doesn't over-explain Flask.
- It includes the map, which gives the assistant a frame for reasoning about files it can't see.
- It asks one question about one path.
- It tells the assistant to name missing files, which turns a silent guess into a visible gap.
- It requires a file and function citation for each step, which gives you something concrete to check.
Tag each file with its path. Without paths, the assistant may merge two files with similar names or lose track of where a function lives.
Decide what to share
You can rarely share everything. This table gives a starting policy.
| File type | Share it? | Reason |
|---|---|---|
| Entry point for the path | Always | It anchors the trace |
| Functions called directly on the path | Usually, in full | The assistant needs real behavior, not names |
| Type definitions and models | Yes, often trimmed to signatures | They explain data shape cheaply |
| Deep helpers (logging, formatting) | Usually no | They rarely change the explanation |
| Configuration that changes behavior | Yes, with secrets removed | Flags and defaults often decide which branch runs |
| Tests for the path | Yes, if short | They show intended behavior with concrete inputs |
| Generated or vendored code | No | It adds noise |
Tests are underrated here. A test that calls create_order with a particular input and asserts a particular result tells the assistant, and you, what the code is supposed to do.
Know the multi-file failure modes
Multi-file questions produce a particular set of errors. Watch for these when you read the answer.
- Invented definitions. The assistant describes what
payments.client.charge()does based on its name. If you didn't share that file, treat the description as a guess, even when it sounds specific. - Wrong file attribution. A behavior is attributed to the wrong module, usually because two files define similarly named functions.
- Missed overrides. A subclass, a decorator, or a configuration value changes the behavior of the code you shared. The assistant explains the default path and misses the override.
- Stale reading. If you pasted one version of a file and later edited it, the assistant is explaining old code. This is common in long conversations.
- Smooth summaries of mixed quality. A trace across five files may be right in four steps and wrong in one. The fluent tone is the same throughout, so you can't judge accuracy from how confident the answer sounds.
Your protection is the citation rule from the prompt template. If every step names a file and function, you can check each step in a few seconds.
Follow up on the seams
Follow-up questions in multi-file work should target the seams, the places where one file hands off to another. Good follow-ups include:
- "In step 3,
service.createcallspublisher.send. What does it pass, and what happens if that call raises?" - "Which step in your trace relied on code I didn't share?"
- "List every place in the files I gave you where the
retry_limitsetting is read." - "Where could this path behave differently if
PAYMENTS_MODEissandbox?"
When the assistant says it needs another file, share that one file, not the whole directory. Then ask it to redo only the affected steps and say whether anything earlier changes.
Verify against the whole project
For single-file code you can run the snippet. For a multi-file path, use tools that work at project scale.
Search confirms where things are defined and used. If the assistant says publish_event is called from the service layer, check:
grep -rn "publish_event" --include="*.py" .Count the results against the claim. If the assistant said it is called once and grep shows four callers, your picture is incomplete.
Running confirms the order of steps. Add temporary log lines or use a debugger breakpoint at the entry point, then step through. Or use an existing test that exercises the path, and run it with verbose output. The order in which calls actually happen is the best evidence for or against the assistant's trace.
Tests confirm intended behavior. If the assistant claims that a failed payment leaves no order row, write a small test that forces a payment failure and inspects the database. If the test passes, you've verified the claim. If it fails, you've found something worth understanding.
Compare each of these results to the trace. A mismatch is useful: it tells you exactly which step to ask about next.
Keep a running summary
Long conversations about large projects drift. Early context gets less attention, and you may no longer remember what you established. Every so often, ask the assistant for a short summary of what is confirmed so far, and then edit it yourself.
Summarize what we've established about the order-creation path in under 10 lines. Mark each line as "confirmed from code I shared," "inferred," or "unknown." Then list the files I should open myself to check the inferred lines.Paste that summary at the top of a new conversation when the old one gets long. A fresh conversation with a short, checked summary and the relevant files often works better than a long thread full of corrections. Keep the same summary in your own notes, since the next chapter covers recording what you learned.
Common mistakes
- Pasting the whole repository instead of choosing a path.
- Asking "how does this project work?" and getting a generic answer.
- Leaving out configuration that decides which branch runs.
- Accepting a description of a function you never shared.
- Not re-sharing a file after you edit it.
- Treating the import map as complete when the project uses dynamic loading.
Exercise
You share api/routes.py and orders/service.py with an assistant and ask how POST /orders works. Its answer says "payments.client then charges the card and retries up to three times on timeout." You never shared payments/client.py. What should you do, and how would you check the claim?
Show answer
Treat the retry detail as unverified, because the assistant could not have seen that code. Ask which steps relied on files you didn't share, then share payments/client.py and ask it to redo only that step. Independently, search for the behavior with grep -rn "retry" payments/ and check for a retry count. You can also run or write a test that forces a timeout and counts the attempts. If the file shows no retry logic, the earlier claim was a guess based on the function name.
Exercise
Why is it better to ask for a trace of one request path than to ask "explain this project"?
Show answer
A single path limits the files you must share to the ones it touches, so the assistant works from real code instead of guessing. It also gives a concrete outcome to check by running, searching, or testing. A project-wide question invites a generic summary with no way to verify it.