Sub topic 1
What goes wrong: invented, mis-signed, and outdated API calls
AI coding assistants write code that looks right but fails when you run it. This chapter names the four kinds of failure so you can tell them apart. Later chapters cover the checks for each.
Prerequisites
- Working knowledge of Python or a similar language
- Basic use of a package manager such as pip
- Familiarity with running unit tests
- Experience reading library documentation
Why the errors look convincing
A code model predicts likely text. It does not look up your installed library. If a name fits the pattern of a library, such as get_json next to get, the model may produce it with full confidence. The code reads well, so a quick review often misses the problem.
The four failure modes
| Failure mode | What the code does | How it shows up |
|---|---|---|
| Invented API | Calls a function, class, or attribute that does not exist | `AttributeError` or `ImportError` |
| Wrong signature | Calls a real function with arguments it does not accept | `TypeError`, or a silently ignored argument |
| Outdated usage | Uses something that worked in an older version | Deprecation warning or an error on newer versions |
| Nonexistent package | Suggests installing a name that is not on the package index | Install failure, or a look-alike package |
Invented APIs
The model fills a gap with a plausible name. The requests library has no get_json function:
import requests
# Invented API: the requests module has no get_json function.
# data = requests.get_json("https://example.com/api")
# Real API: call get, then decode the body with Response.json().
response = requests.get("https://example.com/api", timeout=10)
data = response.json()The invented call fails the first time it runs. That is the best case. Invented code on a rarely used path can survive until production.
Wrong signatures
Here the function exists, but the arguments are wrong. A common example is a plausible keyword argument:
import json
data = {"name": "Ada", "langs": ["python", "c"]}
try:
print(json.dumps(data, pretty=True)) # not a real parameter
except TypeError as error:
print("TypeError:", error)
print(json.dumps(data, indent=2)) # the real parameterThis one fails loudly. Other signature errors do not. A function that accepts **kwargs may ignore a wrong option, and the code then runs with the wrong behavior.
Outdated usage
The call was valid once. Models learn from code written over many years, so they often reproduce old idioms. DataFrame.append was removed in pandas 2.0:
import pandas as pd
rows = [{"id": 1}, {"id": 2}]
# Outdated: DataFrame.append was removed in pandas 2.0.
# df = pd.DataFrame()
# for row in rows:
# df = df.append(row, ignore_index=True)
# Current: build the frame in one step, or use pd.concat.
df = pd.DataFrame(rows)Outdated code may also run today and fail after an upgrade. datetime.utcnow() is deprecated as of Python 3.12 and returns a naive datetime, which has no timezone attached:
from datetime import datetime, timezone
# Deprecated since Python 3.12: naive UTC timestamp.
# now = datetime.utcnow()
# Preferred: timezone-aware timestamp.
now = datetime.now(timezone.utc)Nonexistent packages
An assistant may tell you to pip install a package that does not exist. Someone can then register that name with malicious code. Treat every suggested package as unverified. Chapter 9 covers this.
Where each failure appears
The diagram shows when each kind of failure usually surfaces. The earlier it surfaces, the cheaper it is to fix.
A habit to start now
Do not ask whether the code looks right. Ask which names in it you have confirmed exist in the version you run. The rest of this tutorial builds that habit into tools: introspection, versioned docs, static analysis, warning filters, tests, and CI.
Exercise
An assistant gives you df = df.append(row, ignore_index=True) and the script runs without errors on your older pandas 1.5 machine. Which failure mode is this, and why is a passing run not enough?
Show answer
It is outdated usage. DataFrame.append was removed in pandas 2.0, so the code works only on older versions and fails after an upgrade. A passing run on one installed version says nothing about other versions. Check the version you deploy with and prefer pd.DataFrame(rows) or pd.concat.
Exercise
You see json.dumps(data, pretty=True) in generated code. Is this an invented API, a wrong signature, or outdated usage? What is the real argument?
Show answer
It is a wrong signature. json.dumps exists, but pretty is not one of its parameters, and it raises TypeError. The real argument is indent, for example json.dumps(data, indent=2).