Sub topic 9
Check the explanation against the code
This chapter assumes you can read Python, have used a chat or terminal assistant, and can run small snippets locally. An assistant's explanation is a claim about the code, and you can test it. This chapter covers three ways to do that: run the code, read the documentation, and write a small test.
Turn the explanation into claims you can test
Start by pulling out the specific statements the assistant made. "It caches results" is vague. These are testable:
- Calling
fib(30)computes each value from 0 to 30 once. - Repeated calls with the same argument return the stored result.
- With
maxsize=None, the cache never evicts entries.
Each claim should predict something you can observe. If you can't say what you would see when the claim is true or false, rewrite the claim until you can.
Check 1: run the code and observe
Running the code is the fastest check. Add output that exposes the behavior the assistant described. Here the decorator provides cache_info(), which reports hits and misses.
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 followed by CacheInfo(hits=28, misses=31, maxsize=None, currsize=31).
Compare this with the claim. There are 31 misses because each value from 0 to 30 is computed once. There are 28 hits because each value from 2 to 30 asks for fib(n - 2) after fib(n - 1) has already filled the cache, except at the base of the recursion. The numbers match the "computed once each" claim. Without the decorator, the same call would make over a million recursive calls.
Call fib.cache_clear() between experiments. Otherwise a second run reports hits from the first.
Check 2: read the documentation
Running code shows what happens. Documentation tells you what is guaranteed. Use it for claims about configuration, version differences, and edge cases that your run might not trigger.
For lru_cache, the official functools documentation confirms several details you can't see from one run:
- The cache is keyed on the arguments, so arguments must be hashable.
maxsize=Nonedisables the least-recently-used eviction, so the cache can grow without bound.- Newer Python versions also offer
functools.cacheas a shorthand for the same unbounded behavior.
Read the page for your Python version. If the assistant said "this behaves the same on all versions" and the docs list a change, you have found a claim to correct.
Check 3: write a small test
A test pins a claim down so it stays checked. Write one that fails if the claim is false.
from functools import lru_cache
calls = 0
@lru_cache(maxsize=None)
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
def test_each_value_computed_once():
fib.cache_clear()
global calls
calls = 0
assert fib(20) == 6765
assert calls == 21
fib(20)
assert calls == 21
def test_unhashable_argument_fails():
try:
fib([1, 2])
except TypeError:
return
raise AssertionError("expected TypeError")
if __name__ == "__main__":
test_each_value_computed_once()
test_unhashable_argument_fails()
print("all claims hold")The counter calls counts real executions of the function body, which cached hits skip. The second test checks the documentation claim about hashable arguments.
Choose the right check
| Kind of claim | Best check |
|---|---|
| What the code outputs | Run it |
| How often something executes | Add a counter or log, then run |
| Behavior of a library function | Read the documentation for your version |
| Behavior on unusual input | Write a small test |
| Claims about Python version or configuration | Documentation, then run on your version |
When the check disagrees
If your result differs from the explanation, do not silently fix your notes. Go back to the assistant with the evidence: paste the output and ask it to reconcile the difference. Also check your own setup. A different Python version, a modified copy of the code, or a stale cache can explain a mismatch.
Exercise
You run fib(30) twice in the same session without calling cache_clear(). The second cache_info() shows hits=29, misses=31, not hits=28. Does this contradict the claim that each value is computed once? What does the extra hit show?
Show answer
No. The misses stay at 31, so each value was still computed only once. The second call fib(30) was answered directly from the cache, which added one hit. The result matches the caching claim. To get the first-run numbers again, call fib.cache_clear() before the run.
Exercise
The assistant says "lru_cache keeps only the 128 most recent results." Which check settles this for the code above, and what do you expect to find?
Show answer
Read the documentation for functools.lru_cache. The default maxsize is 128, but this code passes maxsize=None, so there is no limit. You can also confirm by running fib(200) and checking that cache_info().currsize is 201.