Sub topic 7
Turn deprecation warnings into failures
This chapter assumes you can write and run Python unit tests with pytest, install packages with pip, and read library documentation. It also assumes you have already pinned your library versions, as covered in the earlier chapter on version context.
Why deprecation warnings matter for generated code
A deprecation is a notice from a library's authors that some feature still works today but will be removed later. AI assistants often produce deprecated calls. Their training data contains years of code written against older library versions, and deprecated calls were valid in those versions.
Deprecated code is a weaker failure than an invented API. It runs, and the output looks right. The warning is the only evidence of the problem, and Python hides most of it by default. Your code can pass every test and still break on the next library upgrade.
The fix is to make the warning loud. You tell Python to raise an exception when a deprecated call runs, so the problem fails a test run in the same way a wrong function name does.
How Python reports deprecations
Python's warnings module sends messages through a filter. The filter decides whether each warning is shown, ignored, or raised as an exception. Libraries choose a warning category when they emit a message. These are the categories you will meet most often:
| Category | Intended audience | Shown by default? |
|---|---|---|
| `DeprecationWarning` | Developers of code that calls the feature | Only when triggered by code in `__main__`, and under test runners such as pytest |
| `PendingDeprecationWarning` | Developers, for features that will be deprecated later | No |
| `FutureWarning` | End users of an application | Yes |
| `UserWarning` | Anyone | Yes |
The default filters mean a DeprecationWarning raised inside a library you imported is usually invisible when you run a script. A function in your own __main__ module that triggers it will show the message. A call that passes through another module will not. Generated code is often organized into modules, so the warning disappears at the moment you most need it.
Pytest changes this. It collects warnings during a test run and prints a summary at the end. That is useful, but a summary at the bottom of a long log is easy to ignore, and the run still exits with a success code.
Turn the warning into an exception
The warnings.simplefilter function replaces the filter rules. Passing "error" makes matching warnings raise exceptions.
import warnings
warnings.simplefilter("error", DeprecationWarning)
# Any deprecated call executed after this line now raises an exception
# instead of printing a warning that is easy to miss.The effect is global for the running process. After this line, the first deprecated call raises a DeprecationWarning as an exception, with a traceback pointing at the offending line.
Here is the deprecated timestamp call from earlier chapters, caught this way. It needs Python 3.12 or later, where datetime.utcnow() emits the warning.
import warnings
from datetime import datetime
warnings.simplefilter("error", DeprecationWarning)
try:
now = datetime.utcnow()
except DeprecationWarning as exc:
print("Caught:", exc)On Python 3.12 or later this prints a message saying datetime.utcnow() is deprecated and recommending datetime.now(datetime.UTC). On Python 3.11 and earlier no warning is emitted, so nothing is caught. The check is only as good as the interpreter and library versions you run it on.
The preferred form returns a timezone-aware value:
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)The two calls also return different kinds of value. utcnow() returns a naive datetime with no timezone attached, and now(timezone.utc) returns an aware one. Comparing or subtracting one kind from the other raises TypeError. When you replace a deprecated call, check that the new return type fits the code around it.
Apply the filter to a whole test run
Setting the filter inside your code is a blunt tool. For tests, it is better to leave the source files alone and set the filter from outside. The -W option of the Python interpreter does this:
python -W error::DeprecationWarning -m pytestThe format of the option is action:message:category:module:line. Here only the action (error) and the category are given. The double colon leaves the message field empty. Every deprecation raised during the run becomes a test failure.
A second route is pytest's own configuration. This is the version you commit to the repository so every developer and CI job gets the same behavior:
[tool.pytest.ini_options]
filterwarnings = [
"error::DeprecationWarning",
"error::PendingDeprecationWarning",
]Pytest also accepts the command-line form -W error::DeprecationWarning directly, without the python prefix. Both routes apply the same rules, and the configuration file is easier to keep consistent.
Handle noise from third-party code
Turning on strict mode in an existing project often produces a wall of failures. Some come from code you generated or wrote. Others come from a dependency that triggers a deprecation inside its own code, or from a plugin that calls a deprecated API in a newer Python. You cannot fix those lines.
Do not turn the strict rule off. Add narrow exceptions instead. Later entries in filterwarnings take priority over earlier ones, so place exceptions after the general rule:
[tool.pytest.ini_options]
filterwarnings = [
"error::DeprecationWarning",
"ignore:.*pkg_resources.*:DeprecationWarning:some_plugin",
]The ignore entry matches on a message pattern, the category, and the module that raised the warning. Keep each exception as specific as you can, and write a comment next to it naming the dependency and the version that should fix it. A broad ignore::DeprecationWarning removes the whole benefit.
Review the exceptions list each time you upgrade dependencies. An entry that no longer matches anything is dead weight and should be deleted.
A worked example with pandas
Suppose an assistant writes this helper to collect results into a table. It uses DataFrame.append, which was removed in pandas 2.0 after a deprecation period in the 1.x series:
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)The outcome depends on the installed pandas version:
- On pandas 1.4 or later in the 1.x series, the old form works but emits a
FutureWarning. Pandas usesFutureWarningfor this one, which is a reminder that the category table above is a guide and not a promise. A rule that covers onlyDeprecationWarningwill miss it. - On pandas 2.0 or later, the call raises
AttributeErrorbecause the method no longer exists.
This is why the version chapter came first. The same generated code is a quiet warning on one machine and a hard failure on another. If your test environment runs the older version while production runs the newer one, strict warnings in tests are the only early signal.
To cover this case, include the other categories that libraries use for the same purpose:
[tool.pytest.ini_options]
filterwarnings = [
"error::DeprecationWarning",
"error::PendingDeprecationWarning",
"error::FutureWarning",
]Be aware that FutureWarning is also used for behavior changes that are not deprecations of a call. Turning it into an error may flag things you decide to accept. Start with the three categories and add narrow ignores as you review each one.
Where the filter does not reach
Strict warnings only catch code that runs. Keep these limits in mind:
- Untested paths. A deprecated call inside a branch your tests never reach never emits the warning. This links to the coverage points in the next chapters on testing.
- Warnings emitted once. The default filter action
defaultshows a warning once per location. Under theerroraction each occurrence raises, but some libraries cache or deduplicate their own warnings. If a warning seems to disappear on the second test, check for that. - Libraries that do not warn. Some projects remove features with no deprecation period, or change behavior without any message. Silence does not prove the code is current. Read the changelog as described in the documentation chapter.
- Subprocesses. The
-Wflag applies to the interpreter you started. A child process launched by your tests has its own filters unless you passPYTHONWARNINGSin its environment. - Python-version warnings. The Python version decides which standard-library deprecations appear. Run CI on the same Python version you deploy, or on the newest one you support.
A diagram of the flow
A routine you can reuse
- Pin your versions and record them, so the warnings you see match what production runs.
- Add
filterwarningswitherrorfor the deprecation categories to your pytest configuration. - Run the suite once and sort the failures into your code, generated code, and third-party code.
- Fix the first two groups. Add narrow, commented ignores for the third.
- When an assistant produces new code, run the tests again. A new failure that names a deprecated call is a prompt to open the changelog for that library version.
- When you upgrade a dependency, remove ignores that no longer match.
Exercise
Your pytest run passes, but the summary at the end lists several DeprecationWarning messages from code an assistant wrote. What setting would make those cases fail the run, and why can a rule limited to DeprecationWarning still let some outdated calls through?
Show answer
Add "error::DeprecationWarning" to the filterwarnings list in the pytest configuration, or run python -W error::DeprecationWarning -m pytest. Any deprecated call that runs then raises an exception and fails the test. The rule can still miss calls because libraries choose their own warning category. Pandas, for example, used FutureWarning for the deprecation of DataFrame.append, so you also need to consider FutureWarning and PendingDeprecationWarning. Calls on code paths the tests never run, and features removed with no warning, are also missed.
Exercise
On Python 3.11, a strict-warning test run does not flag datetime.utcnow(), but CI on Python 3.12 fails. What explains the difference, and what is the fix in the code?
Show answer
The deprecation of datetime.utcnow() was added in Python 3.12, so earlier interpreters emit no warning for it. The strict filter has nothing to turn into an error on 3.11. Replace it with datetime.now(timezone.utc), then check any code that compares the result with naive datetimes, because the new value is timezone-aware and mixing the two raises TypeError. Run local tests on the same Python version as CI.