Sub topic 2
Why generated code drifts from the library you have installed
This chapter assumes you can read and write Python, install packages with pip, and read library documentation. It explains why an AI assistant can write code that was correct at some point and still fails against your environment. The later chapters in this tutorial cover the checks. Here the goal is a working model of the cause, so you know where to look.
Drift is a version mismatch
Generated code can fail in two ways that look alike. An invented API never existed in any version, such as requests.get_json. A drifted API did exist in some version, but it is not the one you have installed.
Drift is harder to spot because the code looks right. A colleague may have written the same call two years ago. Searching for it turns up blog posts, answers, and documentation pages that use it. The call is real. It just belongs to a different release than the one you are running.
Three versions are involved:
- The library version the model saw most often while it was trained.
- The library version that was current when you asked.
- The library version installed in your environment.
These three are often different. The model does not know the third one unless you tell it.
Where the mismatch comes from
A training cutoff
A language model learns from a snapshot of text collected up to a cutoff date. Anything released after that point is absent or thinly covered. Models are usually released some months after their cutoff, and people keep using them for a long time after release. When you ask for code, the gap between the model's knowledge and the current state of a library is often a year or more.
This is the simplest cause. A library ships a new major version, and a model trained before it will not know the new interface.
More old code than new code
The cutoff is only part of the story. A library that has existed for ten years has ten years of tutorials, forum answers, and open-source repositories. Its newest release has a few months of material. Even a model that saw the new release during training saw far more examples of the old one.
A model produces what is statistically likely, and the likely output reflects the weight of the training data. For a heavily used library, old idioms can outweigh new ones. This is why a model may write a pattern that was deprecated long before its cutoff. The pattern is still abundant in its training data.
Mixed versions in one answer
The training text does not label each snippet with a library version. A model has no reliable way to tell that two calls come from different eras. It can combine a call from an old version with a keyword argument from a new one, or mix two incompatible styles inside one function.
The result may match no release that ever existed. You might call it a hybrid. It fails the way an invented API fails, but it is built from real parts.
Deprecation windows hide the problem
Most libraries do not remove an interface right away. They deprecate it, emit a warning for one or more releases, and later remove it. While the warning period lasts, old code still runs. Your tests may pass and the output may be correct.
That window is when old patterns spread. Code written during it works, so it gets published and copied. The removal comes later, and a model trained on the earlier code will not know it happened.
The model does not see your environment
Unless you supply it, the assistant has no access to your requirements.txt, your lock file, or your Python version. It cannot tell whether you run pandas 1.5 or 2.2. It picks the most probable version and writes for that. If your project has a different one, the mismatch appears only when you run the code.
Some tools can read your project files, and some can browse documentation. That narrows the gap but does not remove it. The tool still has to look at the right file and use what it finds, and the model's habits from training still pull its output toward older code.
Examples of drift
The following table lists well-known changes. Each one was valid code in an older version and fails or warns in a newer one.
| Library | Older pattern | What changed | Typical symptom |
|---|---|---|---|
| pandas | `df.append(row)` | `DataFrame.append` was removed in pandas 2.0 | `AttributeError` |
| NumPy | `np.float`, `np.int` | These aliases were removed in NumPy 1.24 | `AttributeError` |
| Python standard library | `datetime.utcnow()` | Deprecated in Python 3.12 | `DeprecationWarning`, naive datetime |
| SQLAlchemy | `engine.execute(sql)` | Removed in SQLAlchemy 2.0 | `AttributeError` |
A drifted call in practice
The pandas case shows how natural old code looks. This loop builds a table row by row.
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)
print(df)On pandas 1.x, the commented-out loop works, though it is slow because each call copies the whole frame. On pandas 2.0 and later it raises AttributeError. A model that learned from years of 1.x code will often write the loop.
You can see which side of the change you are on by asking the class directly.
import pandas as pd
print(pd.__version__)
print(hasattr(pd.DataFrame, "append")) # True on pandas < 2.0, False on 2.0 and laterThe same code gives different answers in two environments. The code itself is not wrong in an absolute sense. It is wrong for one environment.
Drift that only warns
Not all drift breaks the program. The standard library gives a quieter case.
import warnings
from datetime import datetime, timezone
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
old = datetime.utcnow() # deprecated since Python 3.12
new = datetime.now(timezone.utc)
print([str(w.category.__name__) for w in caught])
print(old.tzinfo) # None: a naive datetime
print(new.tzinfo) # UTC: a timezone-aware datetimeOn Python 3.12 and later, the first list contains DeprecationWarning. On earlier versions it is empty, because the call was not yet deprecated. Either way, old is a naive datetime with no timezone attached. Comparing it with an aware datetime raises TypeError, so a value that looks fine can fail later in a different part of the program.
Here the model's code runs, but it uses a pattern the library's maintainers have steered away from. A later chapter shows how to make such warnings fail loudly.
Drift happens at two levels
Most people think of drift as a change in a function name. It also happens in less visible places:
- Signatures. A parameter is renamed, removed, or made keyword-only. A positional call that used to work now fails.
- Defaults. A default value changes, and the same call returns different results with no error.
- Return types. A function returns an iterator where it used to return a list, or an object where it used to return a tuple.
- Module layout. A class moves to another module, and the old import path stops working.
- Behavior. The call keeps its name and signature but handles edge cases differently.
The last three categories matter most. An AttributeError is a loud failure that you will find quickly. A changed default or return type can pass a quick manual check and produce wrong data, and nothing reports it. That is why existence checks, which a later chapter covers, are necessary but not enough.
What this means in practice
Drift follows from how the model works, so it will not go away with better prompts alone. Several observations help you plan around it.
- Popular, fast-moving libraries drift more. Data science and web frameworks release often and deprecate often. A small stable library may not change for years.
- Major version jumps are the riskiest. Most removals happen at a major version boundary. If your project is on a recent major version, treat suggestions with extra care.
- Confident output is not evidence. The model uses the same tone for a call that exists and a call that does not. The tone tells you nothing about the version.
- Your lock file is the ground truth. The only version that matters is the one your code runs on. Everything else is a guess.
A small habit to start with
You can begin with one line of evidence before any of the checks that come later. Record the Python and library versions in use, so you can compare them with what the generated code assumes.
import sys
from importlib.metadata import version
print(sys.version_info[:3])
print(version("requests"))If the generated code relies on a feature added in some release, this output tells you whether your environment has it. The next chapter covers collecting this information systematically and giving it to the model.
Summary of causes
- A training cutoff leaves the model unaware of newer releases.
- Old code is more abundant than new code, so old idioms are more probable output.
- Training text does not label versions, so the model can mix incompatible eras.
- Deprecation windows let old code keep running and spreading until removal.
- The model cannot see your environment unless you or your tool provide it.
Exercise
A teammate pastes AI-generated code that calls df.append(row, ignore_index=True) in a loop. It runs on their laptop with pandas 1.5 but fails in CI with an AttributeError. Name the most likely cause, and give one line of Python that would confirm it in each environment.
Show answer
The code targets pandas 1.x, and CI has pandas 2.0 or later, where DataFrame.append was removed. The model likely learned the pattern from older code. Running print(pd.__version__, hasattr(pd.DataFrame, "append")) in each environment would show the version and whether the method exists. The laptop prints True and CI prints False.
Exercise
Why can a model write a pattern that was deprecated years before its training cutoff, and why does a successful local run not prove that such code is safe?
Show answer
Old patterns are far more common in the training data than the newer replacements, so they remain the more probable output even after deprecation. A successful run proves little because deprecated calls keep working during the deprecation window. They fail only after a later release removes them, so the same code can break after a routine upgrade.
Exercise
A generated function calls datetime.utcnow() and compares the result to a timezone-aware value. On Python 3.12 it prints a warning and later raises a TypeError. Explain both symptoms and give the preferred call.
Show answer
utcnow() is deprecated as of Python 3.12, which causes the DeprecationWarning. It also returns a naive datetime with no timezone, and comparing a naive datetime with an aware one raises TypeError. The preferred call is datetime.now(timezone.utc), which returns an aware value.