Sub topic 9
Check the explanation against the code
This chapter assumes you can read Python, have used a chat or editor assistant, and can run small scripts locally. The earlier chapters covered how to ask for an explanation. This one covers what to do after you have an answer: treat it as a set of claims, then test each claim against the code.
Why an explanation is a hypothesis
An assistant produces text that sounds right. It does not run your code unless it has an execution tool, and even then it may not run the case you care about. A fluent explanation can still contain a wrong version number, a wrong default value, or a behavior from a different library with a similar name.
Treat the explanation as a list of hypotheses. Your job is to separate the claims that matter from the ones that don't, and to test the ones that matter. You don't need to verify everything. A claim you would build on, or repeat to a colleague, deserves a check.
Turn the explanation into checkable claims
Take the running example from this tutorial:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)Suppose the assistant replies with a walkthrough that includes these statements:
fibreturns the n-th Fibonacci number.- The decorator stores results, so each value of
nis computed once. - The cache is unbounded.
- Calling
fib(30)makes about 31 real computations instead of over a million. - Arguments must be hashable.
- Very large
nis fine because of the cache.
Statement 6 sounds plausible and is wrong in a default setup. The cache removes repeated work, but the recursion still goes n frames deep. Writing the claims out as a numbered list is the first step, because a vague impression such as "it caches stuff" cannot be tested.
Sort each claim by what kind of evidence settles it:
| Claim type | Example | Best check |
|---|---|---|
| Observable behavior | Each `n` is computed once | Run the code and inspect state |
| Default values and signatures | `maxsize=None` means unbounded | Read the official documentation |
| Version-dependent behavior | `functools.cache` exists | Check your interpreter version and the docs' "added in" notes |
| Edge cases | Unhashable arguments fail | Write a small test that triggers the case |
| Intent ("why the author did this") | The decorator avoids slow recursion | Check version control history, comments, and the author |
The last row cannot be settled by running code. An assistant can only infer intent from what it sees, so confirm it with the commit history or a person when it matters.
Verification workflow
The steps below form a loop. If a check contradicts the explanation, tell the assistant what you observed and ask it to revise.
Check 1: run it and inspect state
The cheapest check is to run the code and look at something the explanation predicts. The decorator exposes cache_info(), which reports hits, misses, and current cache size.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(30))
print(fib.cache_info())The output is:
832040
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)You can check this against the explanation. There are 31 misses because the values 0 through 30 are each computed once. There are 28 hits because each of the 29 computations for n from 2 to 30 makes two recursive calls. That is 58 calls plus the top-level call, 59 in total, and 59 minus 31 misses leaves 28 hits. Claims 2, 3, and 4 are now backed by observed numbers. maxsize=None in the output also confirms the cache is unbounded.
Compare this with a wrong claim. An assistant might say "the cache keeps the 128 most recent results." That is the default for a bare @lru_cache. This code passes maxsize=None, so the default doesn't apply. The maxsize field in the output shows the difference.
Check 2: read the documentation
Some claims can't be observed from one run. Defaults, version history, and guarantees belong in the documentation. For standard library behavior, read the page for your Python version, not just the latest one. Look for three things:
- Signature and defaults. The docs state that
maxsizedefaults to 128 and thatNonedisables eviction. - Version notes. Phrases such as "Added in version 3.9" tell you whether a feature exists on your interpreter. Compare against
python --version. - Stated limits. The docs say the arguments must be hashable, and that the cache is keyed on arguments.
If an assistant cites a function, parameter, or flag, search for that exact name in the docs. When the name does not appear, treat the claim as unreliable until you find another source. Invented parameters are a common failure.
If the assistant has quoted documentation, don't trust the quote. Open the page and compare the text.
Check 3: write small tests
A test makes a check repeatable and records what you learned. Write one small test per claim. The script below uses only plain assert statements, so it runs without a test framework.
import sys
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
def check_cache_counts():
fib.cache_clear()
assert fib(30) == 832040
info = fib.cache_info()
assert (info.hits, info.misses) == (28, 31)
def check_unbounded():
assert fib.cache_info().maxsize is None
def check_unhashable_arguments():
try:
fib([5])
except TypeError as exc:
print("TypeError:", exc)
else:
raise AssertionError("expected TypeError")
def check_recursion_limit():
fib.cache_clear()
print("recursion limit:", sys.getrecursionlimit())
try:
fib(5000)
except RecursionError:
print("RecursionError at n=5000")
else:
print("no error at n=5000")
if __name__ == "__main__":
check_cache_counts()
check_unbounded()
check_unhashable_arguments()
check_recursion_limit()
print("all checks done")Note the call to fib.cache_clear() at the start of the count test. Without it, a cache filled by an earlier call would change the hit and miss numbers, and the test would fail for a reason unrelated to the claim. Resetting state before a test is a habit that prevents false alarms.
The last check does not assert anything. It prints what happens, because the result depends on configuration. With the default recursion limit of 1000, fib(5000) needs about 5000 nested calls and raises RecursionError. Someone who raised the limit with sys.setrecursionlimit could see different behavior. This is the case the sample prompt asks about when it requests "which parts depend on Python version or configuration." When a claim depends on the environment, record the environment alongside the result.
Choosing the right check
Different claims call for different checks, and the cost varies.
- Run and inspect is quick and suits claims about what the code does with inputs you can supply.
- Documentation suits defaults, signatures, and version support. It can't tell you what your project's code does.
- A test costs more to write but stays in the repository, so it keeps catching regressions and documents the behavior.
- Version control and people suit questions of intent. Use
git logandgit blameon the line, and read the pull request that introduced it.
Prefer a check that can fail. Running fib(5) and seeing 5 confirms almost nothing, because many wrong explanations would predict the same output. The count check above can fail if the explanation about caching is wrong, so it carries real information.
Common mistakes when verifying
- Checking only the happy path. Test an empty input, a negative number, an unhashable argument, or a very large value. Most wrong explanations survive typical inputs and fail at the edges.
- Running different code than you asked about. If you paste a simplified copy into a scratch file, differences from the real file can hide the behavior. Run the code in its real module when you can.
- Asking the assistant to confirm itself. "Are you sure?" usually gets agreement or a rewrite, and neither is evidence. Ask for something you can execute, then run it.
- Trusting predicted output. An assistant may state exactly what a program prints. Predictions of output are claims too. Run the program and compare.
- Ignoring the environment. Interpreter version, installed package versions, and environment variables change behavior. Note them when a result surprises you.
Run unfamiliar code safely
Verifying means executing code you did not write, so take care first. Read the code you are about to run. Look for network calls, file deletion, writes to shared locations, and database connections. Run it in a virtual environment or a container, with test data and no production credentials. If the code needs a live service to run, check the claim by reading instead, or by stubbing the service in a test. An assistant's suggestion to "just run it" doesn't change this.
Feed the results back
When a check contradicts the explanation, give the assistant the evidence. Paste the output and the code you ran, state which claim it conflicts with, and ask for a corrected explanation. For example:
You said fib(5000) works because of the cache. I ran it with Python's default settings and got a RecursionError. Here is the script and the traceback. Why does the cache not prevent this, and what would change it?Concrete evidence gives the assistant something to reason from, and the revised answer is usually better than the first one. Then repeat the loop on the new claims, because the revision can introduce fresh errors.
What to record
Once a claim passes, write down the claim and how you checked it. A short note such as "unbounded cache, confirmed via cache_info().maxsize on Python 3.12" is enough. The final chapter covers notes in more detail. Keep the test file if the behavior matters to your project.
Exercise
An assistant says: "Because fib uses @lru_cache(maxsize=None), fib(5000) is safe and returns quickly." Name one part of this claim you can check by reading documentation, one part you should check by running code, and what result would contradict the claim.
Show answer
Reading the documentation confirms that maxsize=None means the cache never evicts entries, so the "unbounded cache" part is documented behavior. Running fib(5000) in a scratch script checks the "safe" part. The cache removes repeated work but does not reduce recursion depth, so with the default recursion limit of 1000 the call raises RecursionError. A RecursionError contradicts the claim. You can also print sys.getrecursionlimit() to record the configuration the result depends on.
Exercise
You run fib(30) and fib.cache_info() reports hits=28, misses=31. The assistant had said there would be 30 misses. Explain which is right and why, and what you would send back to the assistant.
Show answer
The observed value of 31 misses is right. The values 0 through 30 are each computed once, which is 31 distinct arguments. The assistant's count was off by one. Send back the script, the CacheInfo output, and a note that the miss count is 31 because n = 0 is also a distinct cached call, then ask it to correct the explanation and recheck any other counts it derived from the same reasoning.
Exercise
Write a check that confirms calling fib with a list argument fails, and say why the test should clear the cache or avoid depending on cache state.
Show answer
Call fib([5]) inside a try block and expect a TypeError, as in check_unhashable_arguments above. The error is raised because lru_cache builds a key from the arguments and a list is unhashable. The call fails before the cache state matters, but tests that count hits and misses must call fib.cache_clear() first. Otherwise earlier calls change the counts and the test fails for reasons unrelated to the claim.