Sub topic 7
Reading generated code before you accept it
This chapter assumes you can write functions, conditionals and loops in Python, run a script in a terminal, and have used a chat-based AI assistant. It covers how to read code an AI gives you before it goes into your project. The next chapter covers how to check that code with tests you write.
Why reading comes first
Generated code usually looks finished. It has sensible names, tidy formatting and often a confident comment. That surface quality is the main risk. Code that looks professional is easy to accept without understanding, and an AI's output can be wrong in ways that are not visible at a glance.
Reading is also where learning happens. If you paste code in and move on, you have the result but not the skill. If you read it line by line and can say what each part does, you have practiced the same skill you will need when you write code without help.
The goal of this chapter is a repeatable reading routine. You do not need to be an expert. You need to be systematic.
A reading routine
Use these steps in order. Each one is cheap, and together they catch most problems.
- Restate the task. Write one sentence describing what the code should do, including inputs, outputs and what happens on bad input. Do this before you read the code, so you are comparing the code to your own requirement and not to what the code claims.
- Predict, then read. Skim the function signature and guess what the body will do. Then read the body and note where you were wrong.
- Trace with a small example. Pick a tiny input and follow the values by hand, line by line.
- List the assumptions. Note what the code takes for granted: sorted input, non-empty lists, positive numbers, a certain type.
- Check the edges. Ask what happens with empty input, one item, duplicates, very large values, and
None. - Mark what you cannot explain. Any line you cannot explain in your own words is a question for the AI, a search, or the documentation. Do not accept it yet.
Worked example: reading a median function
Suppose you asked an AI for a function that returns the median of a list of numbers. It returns this:
def median(values):
if not values:
raise ValueError("median() requires at least one value")
ordered = sorted(values)
mid = len(ordered) // 2
if len(ordered) % 2 == 1:
return ordered[mid]
return (ordered[mid - 1] + ordered[mid]) / 2Work through the routine.
Restate the task. The median is the middle value of the sorted numbers. For an even count, it is the mean of the two middle values. Empty input has no median, so the function should fail clearly.
Predict, then read. You would expect a sort, a middle index, and a branch for odd or even length. The code has all three. It also has an empty check at the top that you may not have thought of.
Trace with a small example. Take [4, 1, 3, 2].
orderedbecomes[1, 2, 3, 4].len(ordered)is 4, somidis4 // 2, which is 2.- 4 is even, so the code skips the first
return. - It returns
(ordered[1] + ordered[2]) / 2, which is(2 + 3) / 2, or 2.5.
Now take [3, 1, 2]. The sorted list is [1, 2, 3], mid is 1, the length is odd, and the function returns ordered[1], which is 2.
List the assumptions. The values must be comparable and support addition and division. A list containing both numbers and strings would fail inside sorted. The function also uses sorted, which makes a new list, so the caller's list is not changed. That is a good property, and worth noticing.
Check the edges. An empty list raises ValueError. A single item gives mid = 0, odd length, and returns that item. Two items give mid = 1, and the function averages index 0 and index 1. All three behave sensibly.
Mark what you cannot explain. If // was unfamiliar, this is the moment to look it up. It is floor division, which rounds down to a whole number.
What to look for: common problems in generated code
Generated code that runs on the happy path can still have problems. These are the ones to look for.
| Problem | What it looks like | How to spot it |
|---|---|---|
| Off-by-one error | Loops that skip the last item, or an index one too high or low | Trace the first and last iteration |
| Unhandled edge case | Crashes on empty input, `None`, or a single item | Run through your edge list |
| Wrong assumption | Assumes sorted input, unique values, or positive numbers | Write the assumptions down |
| Mutating the input | Calls like `list.sort()` change the caller's data | Look for in-place methods and assignments |
| Invented API | Calls a function or argument that does not exist in your library version | Check the official documentation |
| Silent failure | A bare `except:` that swallows errors and returns a default | Search for `except` and `pass` |
| Over-engineering | Classes, layers or libraries for a ten-line task | Ask what is the simplest version |
| Hidden dependency | Imports a package you have not installed or do not want | Read the import lines first |
Mutating the input
This one is easy to miss, so here it is in code. Both functions return the largest two values, but one has a side effect.
def top_two_bad(values):
values.sort(reverse=True)
return values[:2]
def top_two_good(values):
return sorted(values, reverse=True)[:2]
scores = [5, 9, 2, 7]
print(top_two_bad(scores))
print(scores)
scores = [5, 9, 2, 7]
print(top_two_good(scores))
print(scores)The first call prints [9, 7] and then [9, 7, 5, 2], because list.sort() reordered the caller's list. The second call prints [9, 7] and then [5, 9, 2, 7], because sorted() builds a new list. If you only read the return value, both look correct.
Silent failure
def read_age(text):
try:
return int(text)
except:
return 0This function never crashes, which looks like a strength. But read_age("abc") and read_age("0") both return 0, so the caller cannot tell bad input from a real zero. A bare except: also catches things like KeyboardInterrupt. A clearer version catches only ValueError, and either re-raises with a better message or returns None so the caller can decide.
Check names and APIs against real documentation
AI tools sometimes produce function names, parameters or modules that do not exist, or that exist only in a different version. The code reads well because the invented name sounds plausible.
Whenever generated code calls something you do not recognize, look it up in the official documentation for your version. In Python you can also ask the interpreter directly.
import statistics
print(hasattr(statistics, "median"))
print(hasattr(statistics, "middle_value"))
help(statistics.median)The first line prints True, because statistics.median exists. The second prints False, because there is no middle_value. This kind of check takes seconds and can save an hour of confusion.
Questions to ask the AI about its own code
Reading does not mean working alone. Asking the AI to explain its output is a good use of it, as long as you have read first and can judge the answer. Useful questions include:
- Which line is the most likely to be wrong, and why?
- What inputs would make this function fail?
- What assumptions does this code make about its input?
- Is there a simpler way to write this?
- Which standard library functions does this use, and what do they do?
Treat the answers as claims to check, not facts. The AI can be wrong about its own code, and it can describe what the code was meant to do instead of what it actually does. Your hand trace is the tiebreaker.
The reading flow
The routine above is a loop. If any step fails, you go back to the AI or the documentation, and then read again.
Accepting, changing or rejecting
After reading, you have three options.
- Accept when you can explain every line, the edge cases behave as you expect, and the code fits your project's style.
- Change when the idea is right but a detail is wrong. Make the fix yourself where you can. Fixing a small bug is good practice, and it shows whether you understood the code.
- Reject when the approach is far more complex than the task needs, relies on things you cannot verify, or you cannot explain it after reasonable effort. Ask for a simpler approach, or write your own version and use the AI as a reviewer.
Accepting code you do not understand creates a debt. It will come due when the code breaks and you have to fix it.
Gotchas
- Reading only the comments. Comments and docstrings describe intent. They can disagree with the code, so read the code itself.
- Trusting a passing run. One successful run on one input shows very little. Your trace and your edge list matter more.
- Skimming long output. Long answers hide problems. Ask for the smallest piece that does the job, so you can read all of it.
- Reading only for errors. Also ask whether the code is something you could have written. If not, note which concept you are missing and practice it.
Exercises
Exercise
The function below is meant to return the average of a list of numbers. Trace it with [2, 4, 6] and with [], and name two problems you would raise before accepting it.
def average(values):
total = 0
for v in values:
total += v
return total / len(values)
Show answer
With [2, 4, 6], total becomes 12 and the function returns 12 / 3, which is 4.0. With [], the loop does nothing and len(values) is 0, so the division raises ZeroDivisionError. Problem one is the unhandled empty-input case. The error message does not say what went wrong, so a clear ValueError would be better. Problem two is the undocumented assumptions: the function does not state that values must be numbers, and a list with a string would fail with an unclear TypeError. The built-in sum(values) would also be simpler than the manual loop.
Exercise
A generated snippet calls data.sorted_copy() on a Python list. What should you do before accepting it, and what is the likely outcome?
Show answer
Check the documentation, or run hasattr([], "sorted_copy") in the interpreter. Python lists have no sorted_copy method, so the call raises AttributeError. This is an invented API. The correct built-in is sorted(data), which returns a new sorted list without changing the original.