Sub topic 7
Spot hallucinated APIs and fixes that hide the bug
This chapter assumes you can read a Python traceback, run pytest from a terminal, and use git to inspect and undo changes. It builds on the previous chapter, where you compared an assistant's diagnosis with the evidence. Here you learn to recognize the specific ways an assistant's answer can look right and still be wrong.
An assistant produces text that is statistically likely to follow your prompt. It does not run your code unless you give it a way to. So a fluent, confident answer can contain a function that does not exist, a claim about your code that is false, or a "fix" that makes the error message disappear while the bug remains. Each of these has recognizable signs, and each can be checked cheaply.
The two families of failure
Most bad answers fall into one of two families.
- Invented facts. The answer refers to something that does not exist or does not behave as stated: a function, a parameter, a library version, a configuration key, or a line in your code.
- Suppressed symptoms. The answer changes the code so that the error stops appearing, but the underlying defect is still there, or has moved somewhere harder to find.
The first family is caught by checking claims against authoritative sources. The second is caught by asking what the code now does with the input that used to fail.
Hallucinated APIs
A hallucinated API is a name the assistant presents as real but that does not exist in the version you use. It may exist in another library, in another language, in a different major version, or nowhere at all.
Common forms
- A method that sounds right. For example,
list.safe_get(index)orpandas.DataFrame.drop_nulls(). Polars has adrop_nulls, but pandas usesdropna. The name belongs to a neighbor library. - A real function with an invented parameter. For example,
requests.get(url, retry=3). The function exists. Theretryargument does not. - A removed or renamed feature. The API existed in an older version, and your installed version no longer has it.
- An invented package. The assistant suggests
pip installof a name that does not exist. This is more than a nuisance. Attackers register plausible package names, so installing an unfamiliar name blindly can pull in malicious code. - An invented configuration key or flag. A setting that looks plausible in a config file or on a command line, but the tool ignores it or rejects it.
How to check in under a minute
Do not ask the assistant whether the API is real. It may answer yes with the same confidence it used the first time. Check against something that cannot be persuaded.
- Look the name up in the official documentation for the version you run.
- Ask the interpreter directly.
- Read the installed source or signature.
The standard library gives you tools for steps 2 and 3.
import inspect
import requests
print(requests.__version__)
print(hasattr(requests, "get"))
print(inspect.signature(requests.get))
try:
requests.get("https://example.com", retry=3)
except TypeError as exc:
print("Rejected:", exc)If the script runs offline, the TypeError is raised before any network call, because Python checks the keyword arguments when it binds them to the function. For requests.get, which accepts **kwargs, the unknown retry is passed down to requests.request and then to Session.request, which raises TypeError for the unexpected argument. Read the printed message, not just whether an exception occurred.
For a whole package, help(module), dir(module), and python -m pydoc name show what is actually installed. For pip install suggestions, search the package index, check the project's repository, and look at its release history and download numbers before installing.
Version mismatch
Many hallucinations are version errors. State your versions in the prompt, as the template in the spine does with "Python 3.12". Then verify them yourself:
import sys
from importlib.metadata import version
print(sys.version)
print(version("pytest"))If the assistant's answer cites behavior from "Python 3.8" or "pandas 1.x" and you run something newer, treat the answer as unverified until you read the current docs.
Wrong claims about your own code
The assistant can also invent facts about code you pasted. It may say "line 12 calls normalize() before validate()" when the order is reversed, or describe a function you never shared. This happens most when you paste only part of the code, because the assistant fills the gaps with guesses.
Check each claim about your code against the file. A quick test: for every line number or name the assistant mentions, find it yourself. If it cites a line that does not exist, or a variable that is not in your snippet, the reasoning built on it is suspect.
Fixes that hide the bug
The second family is harder to spot because the program stops failing. Compare these two responses to the average([]) failure from earlier chapters.
def average(values):
try:
return sum(values) / len(values)
except ZeroDivisionError:
return 0This removes the traceback. It also states that the average of no numbers is 0, which is a claim the caller never agreed to. A caller computing the average temperature of an empty set of sensors now gets 0 degrees and carries on. The error moved from a loud crash to a silent wrong answer.
Compare the version from this tutorial's earlier fix:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)This one still fails on empty input, but it fails with a clear message that names the cause and the caller's mistake. Whether that is right depends on the expected behavior you stated in your prompt. If you had said "return None for empty input", then returning None would be correct. The point is that the fix must match a decision you made, not one the assistant slipped in.
Patterns that suppress rather than fix
| Pattern | What it does | Why it is risky |
|---|---|---|
| Broad `try/except Exception: pass` | Swallows the error | Hides this bug and every future one in the block |
| Returning a default such as `0`, `""`, or `None` | Replaces the failure with a value | Callers treat the default as real data |
| Adding `if x is not None` around a crash | Skips the failing code | The reason `x` is `None` is never explained |
| Increasing a timeout or retry count | Waits longer | The slow or failing dependency remains |
| Deleting or loosening an assertion or test | Makes the test pass | The test was reporting a real problem |
| Pinning or downgrading a package without a reason | Avoids the new behavior | Postpones a break that will return on upgrade |
| Special-casing the failing input | Handles only the example you gave | Similar inputs still fail |
None of these is always wrong. A guard for None is correct when None is a valid input. The warning sign is a change that appears with no explanation of why the bad state occurs.
Questions that expose a hidden bug
Ask these of any proposed fix:
- What was the root cause, in one sentence, and which line of the fix addresses it?
- What does the code do now with the input that used to fail?
- Could this change make a different input produce a wrong result without any error?
- Did the fix touch a test, an assertion, or a log level? If so, why?
- Does the diff contain anything you did not ask for?
Question 4 matters in particular. An assistant that is told "make the tests pass" may edit the tests. Review the diff for test files before running them.
A worked example
Suppose you ask about a failing config loader and receive this answer: "Use json.load_safe(path), which returns an empty dict on malformed input."
Apply the checks.
- Does
json.load_safeexist? Run the check below. - If it did, would an empty dict be right? A malformed config silently becoming
{}is a hidden-bug pattern.
import json
print(hasattr(json, "load_safe"))
print([name for name in dir(json) if name.startswith("load")])The output shows False and ['load', 'loads']. The function is invented. Reply with the evidence, not with an opinion:
json.load_safe does not exist in Python 3.12 (hasattr returns False; the module only has load and loads).
Also, I do not want malformed config to become an empty dict, because the app would start with default settings and no warning.
Propose a fix that uses only the standard library and raises a clear error that names the file.A good revision might look like this:
import json
def load_config(path):
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except json.JSONDecodeError as exc:
raise ValueError(f"Config file {path} is not valid JSON: {exc}") from excThis uses only real functions, keeps the failure visible, and uses from exc to preserve the original traceback.
Edge cases
- Plausible but deprecated. The API exists but is deprecated, and running with
python -W erroror reading the release notes shows a warning the assistant never mentioned. - Right API, wrong semantics.
sorted()returns a new list, whilelist.sort()returnsNone. An answer that assignsx = x.sort()uses a real method incorrectly. Real names do not guarantee correct use. - Correct on a different platform. Path, signal, or process behavior can differ between Windows, macOS, and Linux. State your operating system.
- Confident tone, no evidence. Phrases such as "this is definitely the cause" are not evidence. Ask what output would prove or disprove the claim, then produce that output.
- Agreement under pressure. If you push back with a wrong correction, an assistant may agree and rewrite a correct answer into an incorrect one. Verify before and after you disagree.
A checklist to run on every answer
- Every imported module, function, parameter, and flag exists in your installed version.
- Every claim about your code matches the file.
- You can state the root cause in your own words.
- The failing input now produces the behavior you specified, not just silence.
- The diff contains no unrelated changes, and no changed tests or assertions you did not approve.
- Any new dependency is real, maintained, and one you decided to add.
Exercise
An assistant fixes a crash in parse_age(text) by wrapping the body in try: ... except Exception: return 0. The crash stops. Give two separate reasons this is risky, and describe one check you would run before accepting it.
Show answer
First, the broad except Exception hides every error in the block, including unrelated bugs such as a typo in a variable name. Second, returning 0 makes bad input look like a valid age, so callers keep running with wrong data and the failure shows up later, far from its cause. A useful check: call parse_age("abc") and parse_age("") and confirm the result matches the behavior you specified, such as raising ValueError. Then write a test for it, and read git diff to confirm no test was changed.
Exercise
An assistant tells you to call requests.get(url, retries=3) to make a flaky download more reliable. Name two ways to check whether this is valid, without asking the assistant.
Show answer
Look up requests.get in the documentation for your installed version, which lists no retries argument. Or run it in Python: inspect.signature(requests.get) shows only url, params, and **kwargs, and passing retries=3 leads to a TypeError for an unexpected keyword argument. Retries in requests are set by mounting an HTTPAdapter configured with a urllib3 Retry object on a Session.