Sub topic 5
Confirm behavior in versioned docs and changelogs
An existence check tells you that a name is present in the installed library. It does not tell you what the name does, which arguments matter, or whether it will survive the next upgrade. Documentation and changelogs answer those questions, but only if they match the version you run.
This chapter assumes you can read Python and run pip, and that you know how to find the installed version of a library (covered in the previous chapters). It also assumes you have looked up an API in a library's online documentation before.
Why the version of the docs matters
Most projects publish several copies of their documentation. A page titled "latest" or "dev" describes the main development branch. A page titled "stable" describes the newest release. A page labelled with a number describes that release. If you read the wrong copy, you can confirm a call that your environment does not support, or reject one that works.
AI assistants make this worse. An assistant often produces code that matches an older release from its training data. If you then search the web and land on the newest docs, you are comparing two different versions, and neither one is the version you have installed.
Always compare three things:
- The version of the library you have installed.
- The version of the documentation page you are reading.
- The version the generated code was written for, if you can tell.
If these three disagree, you have found the source of the problem before you have run any code.
Find the right documentation
Start from the installed version, then locate the docs for that exact release.
from importlib.metadata import PackageNotFoundError, version
def docs_hint(dist, template):
"""Fill a docs URL template with the installed version of a package."""
try:
installed = version(dist)
except PackageNotFoundError:
return f"{dist} is not installed"
return template.format(version=installed)
print(docs_hint("requests", "https://requests.readthedocs.io/en/v{version}/"))
print(docs_hint("pandas", "https://pandas.pydata.org/pandas-docs/version/{version}/"))The URL patterns above are examples. Each project chooses its own, so confirm the pattern once by using the version switcher on the project's docs site. Hosted docs on Read the Docs usually offer a version menu in the sidebar. Some projects, such as pandas, keep archives of older releases. Some projects publish only "latest", and for those you read the source or the docstrings of your installed copy.
Use the docs that ship with your install
Your installed package carries documentation that can never be the wrong version: its docstrings.
import json
help(json.dumps)Docstrings are shorter than the web docs, but they describe the code you are about to run. They often list parameters, defaults, and notes about changes. Use them as the first check, and use the web docs for fuller explanations.
Python's own docs
The Python standard library docs have a version selector at the top of each page. Pick the interpreter version you run. Python docs also mark history inline with notes such as "Added in version 3.9", "Changed in version 3.11", and "Deprecated since version 3.12". These notes come from Sphinx directives named versionadded, versionchanged, and deprecated. Many third-party libraries built with Sphinx use the same markers, so you can scan a page for them.
Read a changelog for a specific question
A changelog is a list of changes between releases. You rarely need to read all of it. Come to it with one question, such as "was DataFrame.append removed, and when?"
Look for these sections, which many projects follow from the "Keep a Changelog" convention:
| Section | What it tells you about generated code |
|---|---|
| Added | A feature may be new. Code using it fails on older installs. |
| Changed | A behavior or default differs between releases. |
| Deprecated | The call still works but is scheduled for removal. |
| Removed | Code using this fails on versions at or after this release. |
| Fixed | An old bug existed, and code may rely on the buggy behavior. |
Not every project uses these names. Pandas, for example, publishes "What's new" pages per release, and many projects use GitHub Releases pages. The question stays the same: for the symbol in question, which release added it, changed it, deprecated it, or removed it?
Versioning rules help you decide where to look. Under semantic versioning (MAJOR.MINOR.PATCH), breaking changes belong in a major release, and deprecations usually appear in minor releases. Many projects do not follow this strictly, so treat it as a hint and not as a guarantee.
Search a local changelog
If the project has a changelog file in its repository, you can search it for the symbol. This small script prints each mention with the heading it appears under, so you can see the release.
import re
import sys
from pathlib import Path
def find_mentions(path, symbol):
heading = "(before first heading)"
text = Path(path).read_text(encoding="utf-8")
for number, line in enumerate(text.splitlines(), start=1):
if re.match(r"^#{1,3} ", line):
heading = line.strip()
if symbol in line:
print(f"{number}: [{heading}] {line.strip()}")
if __name__ == "__main__":
find_mentions(sys.argv[1], sys.argv[2])Run it as python find_mentions.py CHANGELOG.md append. It assumes a Markdown changelog with # headings. For reStructuredText files, which use underlined headings, the heading shown will be wrong, and you should read the surrounding lines instead.
Search for the name, but also search for its likely replacement. When an entry says "removed append, use concat", the replacement name tells you what the generated code should have used.
A worked example: `DataFrame.append`
Suppose an assistant gives you this code and you run pandas 2.x:
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 verification route goes like this:
- Run
python -c "from importlib.metadata import version; print(version('pandas'))". You see a 2.x number. - Open the docs for that release and search for
DataFrame.append. The API reference page is absent. - Open the release notes for 2.0.0 and search for
append. The entry lists the removal and the replacement,pandas.concat. - Open the notes for 1.4.0, which first deprecated it, to see how long the warning period lasted.
You now know the call is not merely missing. It was removed on purpose, and you know what to use instead. Without the changelog you might have guessed at a fix that only looked similar.
Reading a docs page critically
A page can exist and still mislead you. Check these points before you accept it.
- Page version. Look at the banner or URL. A banner such as "This is documentation for an unreleased version" means the page describes code you may not have.
- Parameter defaults. A default can change between releases. If generated code omits an argument, its default is now part of the behavior you depend on.
- Return type. Some functions changed from returning a list to returning an iterator or a view. Code that indexes the result then breaks.
- Version notes. Look for "added", "changed", and "deprecated" markers near the parameter you use, not only at the top of the page.
- Examples. Examples show intended use, but they may be older than the text around them.
Deprecation messages are documentation too
Runtime warnings often say where to look. A message that states "removed in version X" gives you the exact release to search for in the changelog. The next chapter shows how to turn these warnings into test failures. For now, notice that the warning text is one more source you can cross-check against the docs.
The Python date example works the same way. datetime.utcnow() is marked deprecated since Python 3.12 in the standard library docs, and the replacement is datetime.now(timezone.utc). The docs also explain why: utcnow() returns a naive datetime, one without time zone information.
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)When the docs are silent or wrong
Sometimes the docs have no page for the symbol, even though it exists. Private helpers, undocumented keyword arguments, and newly added features are common cases. Sometimes the docs describe behavior that the code no longer follows.
In those cases, fall back on these sources, in this order:
- The installed source code. Use
inspect.getsourceor open the file insite-packages. - The project's tests, which show supported usage and are written for a specific version.
- The issue tracker, searching for the symbol name and the word "removed" or "deprecated".
- A small experiment that calls the function with known inputs.
Prefer public, documented APIs. A symbol that appears only in source code, with a leading underscore or no docs, can change in any release without a changelog entry. If generated code relies on one, ask for a documented alternative.
Common mistakes
- Reading "latest" docs for an older install. The call appears documented, but your version lacks it.
- Reading old docs for a newer install. You reject a valid new feature, or you keep using a deprecated one.
- Trusting a blog post or answer without a date. Check that its version matches yours.
- Searching only for the old name. Also search for the replacement, since renames are listed under the new name.
- Stopping at the first match. A name can be added, deprecated, and removed across three entries. Read all of them.
Exercise
Your environment has pandas 2.1 installed. An assistant produces code that calls df.append(row, ignore_index=True) inside a loop. Describe the steps you would take to confirm the problem and find the correct fix, naming at least two kinds of source you would consult.
Show answer
First read the installed version with importlib.metadata.version("pandas") and confirm it is 2.1. Open the pandas docs for that version and look for DataFrame.append in the API reference. The page is absent. Then search the release notes ("What's new") for 2.0.0 and find the entry that removed append, which also names pandas.concat as the replacement. Optionally check the 1.4.0 notes for the original deprecation. The fix is to collect the rows in a list and build the frame once with pd.DataFrame(rows), or to use pd.concat. The two source kinds are the versioned API reference and the release notes (changelog).
Exercise
A page of documentation shows a function with a parameter strict. Your installed library is one minor version older than the docs you are reading. Name two things you should check before using strict in generated code.
Show answer
Check the page's version banner or URL to see which release it describes, and check the version notes near the parameter for an "added in version X" marker. Then compare X with your installed version. You can also confirm directly by running inspect.signature on the function in your environment and checking whether strict appears in its parameters.