Skip to main content

Learn to Program in the Age of AI, Part 3: Reading and Reviewing AI-Generated Code (2026)

By Pashalis LaoutarisUpdated: Category: Learn to Program23 min read

When an AI assistant writes your code, you become its reviewer. Nobody else will read it before it runs. If it reads a file it should not, stores passwords badly, or calls a function that does not exist, the mistake ships under your name.

Reviewing sounds like a senior skill, but it is learnable, and beginners can do much of it with a checklist. You do not need to know everything. You need to know which questions to ask, and how to check the answers instead of trusting them.

This is the third article in my series for beginners, career switchers, and junior developers who already use AI tools. Part 1 explained why reading code matters more now. Part 2 showed how to use AI as a tutor. This part gives you a review checklist, a method for reading a function, and practice code to try it on.

As always in this series, I tested it. I asked a local AI model for seven everyday functions, the kind where AI code often goes wrong. It got five of them right every time, which is genuinely good news. The other two failed every time: one let users read any file on the machine, and one called a function that does not exist. Then I asked the same model to review its own code, with and without my checklist. The checklist helped with one flaw and did nothing for the other. The security guidance I cite comes from OWASP and the Python documentation, which I checked on December 1, 2026.

The series

  1. What still matters
  2. Using AI as a tutor, not a ghostwriter
  3. Reading and reviewing AI-generated code (this article)
  4. Debugging without handing everything to the AI
  5. Testing as your safety net
  6. Your first project with an agent

Table of Contents

  1. The Short Answer
  2. Why Review Is Now Your Job
  3. Experiment 1: Seven Everyday Functions
  4. Experiment 2: Can AI Review Its Own Code?
  5. How to Read a Function in Five Passes
  6. The Review Checklist, Explained
  7. Verify, Do Not Just Read
  8. Using AI as a Reviewer, Wisely
  9. Practice: Review These Two Functions
  10. Common Mistakes
  11. Frequently Asked Questions
  12. Conclusion
  13. References

1. The Short Answer

Before you accept AI-written code, go through these questions. Each one is explained in section 6.

# Question What it catches
1 Does it do what was asked, including edge cases? Almost-right code that only handles the obvious case
2 Can input from users or files attack it? File path tricks, SQL injection, shell injection
3 Does every function and method it uses really exist? Invented functions that crash when that line runs
4 What else does it change besides its return value? Shared state, modified arguments, global settings
5 What happens when something fails? Errors that are hidden instead of reported
6 Does it follow current practice for passwords, secrets, and randomness? Weak hashing, guessable tokens, outdated settings
7 Is it more complicated than it needs to be? Code that is hard to read, and therefore hard to check
8 Did anyone actually run it? Demo code and comments that promise untested behavior

The most important habit is the last one. In my experiment, the code that failed came with example code and comments promising it worked. Running it for one second would have shown otherwise.

2. Why Review Is Now Your Job

In a team, code review is a second pair of eyes before code reaches users. When an AI writes the code and you accept it, you are that second pair of eyes, and often the only one.

That changes what reading code means. Part 1 showed the core problem: AI code is usually right, and the wrong answers look just like the right ones. They come with confident comments, tidy structure, and sensible names. The flaws hide in details that a quick skim misses, such as a file path that can point anywhere, or one function call that does not exist.

A checklist turns review from a vague feeling of “looks fine” into specific questions with specific answers. It is also how professional reviewers work. Nobody holds every possible problem in their head. They check the categories that matter.

3. Experiment 1: Seven Everyday Functions

The setup

I asked Gemma 4 (gemma4:e4b), running locally through Ollama, for seven small functions. I phrased each request the way a beginner would, with no hints about security or edge cases. Each request ran three times.

Function The classic trap
Load users from a CSV file Splitting on commas breaks names like “Smith, Jane”
Find a user in a SQLite database Building SQL from text allows SQL injection
Read an uploaded file from a folder A filename like ../secret.txt escapes the folder
Ping a host the user typed in Passing input through a shell allows command injection
Hash and verify passwords Fast hashes, missing salt, or broken comparison
Make a password reset token The random module is predictable
Add an item to a shopping cart A default cart={} is shared between calls

Then I attacked each result. I fed the CSV loader a quoted name with a comma, and tried a classic SQL injection string on the database function. I asked the file reader for ../secret.txt, and called the cart function twice to see if carts leaked into each other. For the ping and token functions, which I did not want to execute, I checked the code for a shell and for the random module.

What the model produced

Function Correct in all 3 runs? What happened
CSV loader Yes Used Python’s csv module, so quoted commas worked
Database lookup Yes Used a parameterized query, so the injection returned nothing
Ping Yes Ran ping with an argument list, without a shell
Reset token Yes Used the secrets module
Shopping cart Yes Used cart=None, so each new cart started empty
File reader No, 0 of 3 ../secret.txt returned the secret file every time
Password hashing No, 0 of 3 Called hashlib.compare_digest, which does not exist

The good news first

Five of seven functions avoided their classic trap every single time, and that matters. AI assistants have clearly learned many of the lessons that once filled security tutorials, such as parameterized queries and the secrets module. You do not need to assume AI code is always dangerous.

You do need to check it, though, because the failures were consistent. When the model got something wrong, it got it wrong in all three runs.

Asking again is not verification. Where the model had a gap, every new attempt reproduced the same wrong pattern. Only an outside check, such as running the code or reading the documentation, broke the cycle.

Failure 1: the file reader

Here is the core of the file reader, exactly as generated.

file_path = os.path.join(base_dir, filename)
try:
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()
except FileNotFoundError:
    print(f"Error: File not found at {file_path}")
    return None

If a user asks for ../secret.txt, os.path.join builds a path that steps out of the upload folder, and the function reads whatever is there. This is called path traversal. In a web app, it can expose configuration files, keys, and other users’ data.

There is a second way in. When the filename is an absolute path, os.path.join throws away the base folder entirely, as Python’s documentation describes. I confirmed it with both the Windows and the Linux and macOS path rules.

os.path.join("uploads", r"C:\secrets\keys.txt")  # Windows result: 'C:\\secrets\\keys.txt'
os.path.join("uploads", "/etc/passwd")           # Linux and macOS result: '/etc/passwd'

In both cases, the upload folder is simply gone from the path.

The code also hides errors. It catches the error, prints a message, and returns None. A caller cannot tell “file not found” from “file was empty,” and in a web server, nobody reads printed messages.

Failure 2: the password functions

The password code made a good start. It used PBKDF2 with a random salt, a real password hashing function, and stored the salt with the hash. Then the verification ended like this.

# Compare the resulting hash with the stored hash securely
return hashlib.compare_digest(key.hex(), stored_key_hex)

There is no compare_digest in the hashlib module. The real function lives in the hmac module, as hmac.compare_digest. So every login attempt crashes with an AttributeError. The comment says “securely,” and the line cannot run at all.

The most telling detail was at the bottom of the file. The model included a demo section that hashes a password, verifies it, and prints the result, with comments saying “Should be True” and “Should be False.” That demo crashes the moment it runs, so nobody ran it. The comments describe what the author hoped, not what happens.

There was a smaller issue too. The code used 100,000 iterations. OWASP’s Password Storage Cheat Sheet currently recommends 600,000 iterations for PBKDF2 with SHA-256, and prefers Argon2id, scrypt, or bcrypt where available. Security settings age, so “current practice” is part of the checklist.

4. Experiment 2: Can AI Review Its Own Code?

Next, I gave the six flawed versions back to the same model, along with the original request, and asked for a review in two ways.

  • Plain: “Review this code for problems.”
  • Checklist: The checklist prompt from section 8. It contains the first seven questions of the reader’s checklist, because the eighth, running the code, is something you do yourself. It includes “Can input from users or files attack it?” and “Does every function, method, and module it uses really exist?”

I also asked it to review three of the correct functions, to see whether it would invent problems.

The review results

Flaw Plain review found it Checklist review found it
Path traversal in file reader 1 of 3 3 of 3
Function that does not exist 0 of 3 0 of 3

The checklist made a real difference for path traversal. Asked specifically about inputs that attack the code, the model named the problem every time.

The invented function was another story. Not one review caught it, even though the checklist asked directly whether every function really exists. Worse, the reviews vouched for the broken line. One checklist review said that the functions used, including compare_digest, “all exist and behave as expected.” A plain review called the compare_digest() call “critical and correctly implemented.”

That pattern makes sense. The same gap in the model’s knowledge that produced the invented function also shapes its review, so it believes in the function both times. Your Python interpreter does not share that blind spot.

What it said about correct code

For the three correct functions, the reviews did not invent bugs. They suggested reasonable additions, such as an expiry time for reset tokens and validation for the cart quantity. But each review ran to between 343 and 600 words for functions of 10 to 20 lines. In a long review, a real finding is easy to miss among the suggestions. Section 8 shows how to ask for shorter, sharper reviews.

5. How to Read a Function in Five Passes

Reading code well is a method, not a gift. Read a function several times, each time asking a different question.

  1. Start with the purpose. Read the name, parameters, and return value. What is this supposed to do? Compare it with what you asked for.
  2. Follow the happy path. Trace one normal input through the code, line by line, and predict the result. Part 1 called this “predict before you run.”
  3. Edge cases and inputs. Now trace the awkward inputs: empty, very large, negative, missing, and malicious, such as ../ in a filename.
  4. Side effects and failures. Look for anything that changes outside the function, and for every try, except, and early return. What happens when something goes wrong?
  5. Check the dependencies last. List every module, function, and method the code uses. For any you have not used yourself, check that it exists and does what the code assumes.

Five passes sounds slow, but each one is quick for a short function. Here is what they look like on the AI’s file reader from section 3.

  1. Purpose: It takes a folder and a filename, and returns the file’s text. That matches the request.
  2. Happy path: read_upload("uploads", "a.txt") joins the path, opens the file, and returns "hello", which is correct.
  3. Edge cases and inputs: What if the filename is ../secret.txt? The joined path leaves the folder, and nothing stops it. That is the bug.
  4. Side effects and failures: A missing file prints a message and returns None, so the caller never learns what went wrong.
  5. Dependencies: os.path.join and open both exist, but reading the documentation for os.path.join reveals the absolute-path behavior.

Applied to the password code, the fifth pass alone would have caught the invented function.

6. The Review Checklist, Explained

1. Does it do what was asked, including edge cases?

Compare the code with the request, not with your impression of it. List the edge cases from the request, then find where the code handles each one. If you cannot find the line that handles an edge case, it probably is not handled. Part 5 of this series turns these cases into tests.

2. Can input from users or files attack it?

Any value that comes from outside your program, such as a form field, a URL, a file, or an API response, should be treated as hostile until proven otherwise. The three classic attacks are these.

  • Path traversal: a filename like ../secret.txt or an absolute path escapes the intended folder.
  • SQL injection: text glued into a SQL query changes the query. Use placeholders, such as ? in SQLite, as the model correctly did.
  • Command injection: text passed through a shell can run extra commands. Pass arguments as a list without shell=True, as the model also did correctly.

Here is a safe version of the file reader. I tested it against both attacks.

from pathlib import Path

def read_upload(base_dir, filename):
    base = Path(base_dir).resolve()
    target = (base / filename).resolve()
    if not target.is_relative_to(base):
        raise ValueError("file is outside the upload folder")
    return target.read_text(encoding="utf-8")

It resolves the full path first, then checks that the result is still inside the upload folder, and that order matters. Python’s documentation notes that is_relative_to only compares the text of the paths and does not treat .. specially, so it must run on the resolved path. The method has existed since Python 3.9, so it is safe to use on any supported version. In my tests, it refused ../secret.txt and an absolute path. It still allowed harmless forms like sub/../a.txt, which ends up back inside the folder.

3. Does every function and method really exist?

AI models sometimes invent functions that sound right, such as hashlib.compare_digest. They also invent parameters, options, and whole library features. For every call you do not know personally, check the official documentation, or simply run the code. A function that does not exist fails the moment its line runs.

4. What else does it change?

A good function’s effects should be obvious from its name and return value. Watch for code that modifies an argument the caller passed in, changes a global setting, writes to files unexpectedly, or uses a mutable default such as cart={}. The model avoided that last trap here, but it is one of the most common Python bugs.

5. What happens when something fails?

Look at every except block. Catching an error, printing a message, and returning None hides problems, as the file reader did. Usually, it is better to let the error propagate, or to raise a clearer one. Be especially suspicious of except Exception:, which catches almost everything, including your own bugs.

6. Does it follow current practice for security-sensitive work?

Passwords, tokens, keys, and randomness need extra care, because the mistakes are invisible in normal use.

  • Passwords: use a dedicated password hashing function. OWASP lists Argon2id first, then scrypt, bcrypt, and PBKDF2, with 600,000 iterations for PBKDF2 with SHA-256.
  • Comparisons of secrets: use hmac.compare_digest, which takes the same time whether the values match early or late.
  • Random tokens: use the secrets module, never random.

Here is the corrected password code. I tested that two hashes of the same password differ, and that verification accepts the right password and rejects a wrong one.

import hashlib, hmac, os

ITERATIONS = 600_000

def hash_password(password):
    salt = os.urandom(16)
    key = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS)
    return f"{ITERATIONS}${salt.hex()}${key.hex()}"

def verify_password(password, stored):
    iterations, salt_hex, key_hex = stored.split("$")
    key = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), int(iterations))
    return hmac.compare_digest(key.hex(), key_hex)

Storing the iteration count with each hash lets you raise it later without breaking existing passwords.

For real applications, do not write this yourself. The corrected code shows what correct looks like, but a maintained library such as argon2-cffi, or your web framework’s built-in password tools, is the better choice. They handle algorithm choice, settings, and upgrades for you, and they have been reviewed far more than any code you or an AI write today.

7. Is it more complicated than it needs to be?

Extra layers, unused parameters, and clever tricks make code harder to review, and code that is hard to review is easy to get wrong. If a simpler version does the same job, prefer it, or ask the AI for it.

8. Did anyone actually run it?

Comments and demo blocks describe what the author intended. Only running the code shows what it does. The password demo said “Should be True” and crashed. Make running the code the last step of every review.

7. Verify, Do Not Just Read

Reading finds many problems. Running the code finds the rest, often faster.

  • Run any demo code. If the AI included an example, run it. In my experiment, that alone would have exposed the password bug.
  • Try the attack yourself. Call the file reader with ../ and an absolute path. Call the database function with ' OR '1'='1, which takes seconds.
  • Check unfamiliar calls in the docs. One search for “hashlib compare_digest” shows it is not there.
  • Use your editor’s tools. Editors with Python support underline many unknown names. Type checkers such as mypy and Pyright are designed to report attributes that a module does not have. I did not run one for this article, but it is worth adding to your setup.
  • Write a quick test. Part 5 covers this in depth, but even three quick checks are better than none.

8. Using AI as a Reviewer, Wisely

AI review is useful, as the path traversal results show. Use it as one reviewer among several, and shape the request.

A checklist prompt

This is the checklist prompt I tested. It found the path traversal in all three runs. It covers the first seven questions from section 1. The eighth, running the code, stays with you.

Review this code using the checklist below. For each item, answer OK or describe the specific problem.
1. Does it do what the task asks, including edge cases and bad input?
2. Can input from users or files attack it? Think about file paths, SQL, shell commands, and HTML.
3. Does every function, method, and module it uses really exist and behave as the code assumes?
4. Side effects and shared state: globals, mutable defaults, modified arguments, printing instead of returning or raising.
5. Error handling: are errors reported, or silently hidden?
6. Security-sensitive choices: passwords, randomness, secrets, and current best practice for them.
7. Is anything more complicated than it needs to be?

Rules for AI reviews

  • Include the original task. A reviewer cannot judge “does what was asked” without knowing what was asked.
  • Never trust “this function exists.” In my test, the model confirmed a function that does not exist. Check unfamiliar calls yourself, in the documentation or by running the code. No prompt wording fixed this, so treat it as a rule, not a tip.
  • Ask for short answers when you need focus. Adding “List only real problems, most serious first, at most five” keeps findings from drowning in suggestions. I did not test this variant, so judge it by the results you get.
  • Ask for specific attacks. “What happens if filename is ../secret.txt?” gets a sharper answer than “Is this secure?”
  • Verify every single finding. A review claim is a hypothesis. Test it, as Part 2 showed with hints.

9. Practice: Review These Two Functions

Try the checklist yourself before reading the answers. Each function has at least one real problem.

Exercise 1

import random, string

def make_reset_token(length=20):
    chars = string.ascii_letters + string.digits
    return "".join(random.choice(chars) for _ in range(length))

Exercise 2

def add_tag(post, tag, tags=[]):
    tags.append(tag)
    post["tags"] = tags
    return post

Answers

Exercise 1 uses the random module, which is designed for simulations, not security. Python’s documentation warns against using it for security purposes. An attacker who sees enough tokens can predict the next ones. Use secrets.token_urlsafe(32) instead, as the model did in my experiment.

Exercise 2 has a mutable default argument. The list tags=[] is created once, when the function is defined, and shared by every call that does not pass its own list. Tags from one post leak into the next. The usual fix is tags=None, then if tags is None: tags = [] inside the function. The same trap applies to {} and set() defaults, and to any other default value that can be changed in place.

If you spotted both problems, you are already reviewing more reliably than the unguided AI reviews in my experiment. If you missed one, go back to the checklist question that covers it, and keep that question in mind next time.

10. Common Mistakes

  1. Skimming instead of reading. Tidy code and confident comments say nothing about correctness.
  2. Trusting comments and demo code. The password demo promised “Should be True” and crashed.
  3. Reviewing without the original request. You cannot check “does what was asked” without it.
  4. Forgetting about malicious input. Most security bugs start with input the author never imagined.
  5. Accepting unfamiliar functions on faith. Check them in the docs, or run the code.
  6. Treating an AI review as the final word. It missed the invented function every time and vouched for it.
  7. Assuming AI code is always dangerous. Five of seven functions were right every time, so review carefully, but fairly.
  8. Never running the code. One run catches what ten readings miss.

11. Frequently Asked Questions

How long should reviewing a function take?

For a short function, a few minutes with the five passes. Security-sensitive code, such as anything touching passwords, files from users, or databases, deserves more time. A slow review is still much faster than cleaning up after a breach.

Do I need to know security to review code?

You need to know the common attack patterns, and the checklist covers the main ones for beginners. The OWASP Cheat Sheet Series is a good free reference when a specific topic comes up.

Should I ask the AI to fix the problems it finds?

You can, but then review the fix too, with the same checklist. For learning, try fixing simple problems yourself first, as Part 2 suggests.

Why did the model fail the same way every time?

When a model has a gap in its knowledge, such as where compare_digest lives, that gap shows up on every attempt. Asking again does not help, because the same knowledge produces the same mistake. A different source of truth, such as the documentation or the interpreter, breaks the cycle.

Is code from a bigger model safe to accept without review?

No, it is not. Bigger models make fewer mistakes, but they still make them, and their mistakes look just as convincing. Rarer mistakes are often harder to notice, because you stop expecting them. Review is how you find out which of the answers is the wrong one.

12. Conclusion

Reviewing AI code is now a core programming skill, and a checklist makes it learnable. Ask whether the code does what was asked, whether input can attack it, and whether every function exists. Then ask what it changes, how it fails, whether it follows current security practice, whether it could be simpler, and whether anyone ran it.

My experiment shows both sides. The model avoided five classic traps every time, which is real progress. It also failed two the same way every time: a file reader that leaks any file, and password code that calls a function that does not exist. Asked to review its own code, it found the first flaw only with a checklist, and it vouched for the second.

So read with a method, verify by running, and treat every review, including the AI’s, as a list of claims to check. The next article covers debugging: what to do when the code you are reviewing fails and you need to find out why. Tools and guidance change, so treat the specifics here as accurate as of early December 2026.

13. References

Security guidance

Python documentation

On this site


Back to All Posts
Share this post:
Share on X
Share on LinkedIn
Share on Reddit
Share on Facebook
Copy Link
Copied!