Sub topic 3
Pin down the versions you are actually running
This chapter assumes you can run Python from a terminal, use pip and virtual environments at a basic level, and read a pyproject.toml or requirements.txt. The goal is to answer one question reliably: which Python, and which version of each library, will execute the code an assistant just wrote for you?
Every later check in this tutorial depends on that answer. An existence check, a docs lookup, and a deprecation warning are only meaningful against a specific version. A function that was removed in pandas 2.0 is fine in pandas 1.5. If you check against the wrong version, you can approve code that fails in production, or reject code that works.
Why "the version" is several different things
When people say "we use requests 2.31", they may mean any of four things. These can disagree, and the disagreement is a common source of confusing errors.
| Source | What it tells you | Typical gap |
|---|---|---|
| Declared requirement (`pyproject.toml`, `requirements.in`) | The range you accept, such as `pandas>=2.0` | Says nothing about the exact version installed |
| Lock file or pinned requirements | The exact versions a resolver chose | Can be stale if nobody regenerated it |
| Installed environment | What is physically on disk in one interpreter | May differ from the lock file if someone ran `pip install` by hand |
| Runtime, in the process | What the running program actually imported | May come from a different interpreter or path than you expected |
The runtime answer is the one that counts, because it is the code that runs. The other three are intentions. Your job is to look at the runtime answer first, then compare it to the intentions.
Step 1: Confirm which interpreter you are using
Most "wrong version" mysteries are really "wrong interpreter" mysteries. A machine often has a system Python, a Homebrew or pyenv Python, and one or more virtual environments. Each has its own installed packages.
Run this from the same shell and directory where you run your tests:
import sys
print(sys.version)
print(sys.executable)
print("in a virtual environment:", sys.prefix != sys.base_prefix)sys.executable is the path of the interpreter that is running the script. If it points to /usr/bin/python3 and you expected .venv/bin/python, every version check you make afterwards describes the wrong environment.
The Python version also matters for generated code. The datetime.utcnow() deprecation applies from Python 3.12. Syntax such as match statements needs 3.10. Type-hint forms like list[int] need 3.9. Record the interpreter version alongside library versions.
Step 2: Read installed versions from package metadata
The most reliable way to read an installed version is the standard library's importlib.metadata. It reads the metadata that pip wrote when it installed the package, so it does not depend on the package exposing any attribute.
from importlib.metadata import PackageNotFoundError, version
for name in ["requests", "pandas", "not-a-real-package-xyz"]:
try:
print(name, version(name))
except PackageNotFoundError:
print(name, "is not installed in this interpreter")Two details cause trouble here.
First, version() takes the distribution name, which is the name you give to pip install. It does not take the import name. The two often differ.
| You write in code | You install with pip |
|---|---|
| `import yaml` | `PyYAML` |
| `import PIL` | `Pillow` |
| `import sklearn` | `scikit-learn` |
| `import cv2` | `opencv-python` |
Distribution names are matched case-insensitively, and -, _ and . are treated as equivalent. So scikit-learn and scikit_learn refer to the same package.
When you only have the import name from a line of generated code, ask the metadata system to translate it. packages_distributions() is available from Python 3.10:
from importlib.metadata import packages_distributions, version
def installed_version(import_name):
"""Return the installed version for an import name, or None."""
dists = packages_distributions().get(import_name)
if not dists:
return None
return version(dists[0])
print(installed_version("yaml"))
print(installed_version("definitely_not_installed"))The second call prints None because no installed distribution provides that module.
Second, do not rely on module.__version__. Many packages define it, but it is a convention and not a guarantee. Some packages omit it. Others set it by hand and forget to update it, and a few expose a different attribute name entirely.
Step 3: Capture an environment report you can reuse
A small script that prints the interpreter and a list of key libraries gives you something to paste into a prompt, a bug report, or a pull request description. It also fails visibly when a package is missing.
import platform
import sys
from importlib.metadata import PackageNotFoundError, version
def environment_report(names):
lines = [
f"python {platform.python_version()}",
f"interpreter {sys.executable}",
]
for name in names:
try:
lines.append(f"{name}=={version(name)}")
except PackageNotFoundError:
lines.append(f"{name}: NOT INSTALLED in this interpreter")
return "\n".join(lines)
if __name__ == "__main__":
print(environment_report(["requests", "pandas", "numpy"]))Save it as envreport.py in the project and run it with the project's interpreter. The output is plain text, so it works in a chat window as well as in a ticket.
Step 4: Ask pip about the whole environment
For a broader view, pip can list everything installed and check for inconsistencies:
python -m pip list
python -m pip show requests
python -m pip freeze
python -m pip checkEach command answers a different question:
pip listshows every installed distribution and its version, in a table.pip show requestsprints one package's version, its location on disk, and which installed packages depend on it ("Required-by").pip freezeprintsname==versionlines in the format of a requirements file.pip checkreports installed packages whose own requirements are not satisfied, for example a library that needsurllib3<2whileurllib3 2.xis installed.
The Location field in pip show is useful when you suspect the wrong environment. If the path is under site-packages of a different Python, you have found the problem.
Direct and transitive dependencies
You declare a handful of libraries. The environment contains many more, because each library pulls in its own dependencies. These indirect ones are called transitive dependencies.
Transitive versions matter for generated code too. An assistant may call a function from urllib3 or numpy that you never listed, because it saw it used through another library. You can see what a package asks for with requires():
from importlib.metadata import requires
for requirement in requires("requests") or []:
print(requirement)This requires requests to be installed, otherwise it raises PackageNotFoundError. Lines containing ; extra == ... describe optional extras and are not installed by default.
Step 5: Pin versions so the answer stays the same
Looking up versions tells you where you are today. Pinning keeps the answer stable, so that a check you ran last week still describes what runs next week. Without pins, a fresh install can pull a newer release that removes or changes the API the generated code uses.
Version specifiers in a requirements file or pyproject.toml work as follows:
| Specifier | Meaning | Use |
|---|---|---|
| `pandas==2.2.2` | Exactly this release | Lock files, deployments |
| `pandas>=2.0,<3` | Any 2.x from 2.0 | Libraries declaring a supported range |
| `pandas~=2.2` | At least 2.2, below 3.0 (compatible release) | Applications that accept minor updates |
| `pandas` | Anything | Avoid in anything you ship |
A reasonable split is to declare ranges in pyproject.toml and to commit a lock file with exact versions. Tools such as pip-tools (pip-compile), uv, Poetry, and PDM generate lock files. They differ in details, but each records exact resolved versions, including transitive ones, so an install on another machine reproduces yours.
A pinned requirements file looks like this:
pandas==2.2.2
requests==2.32.3
numpy==1.26.4Install from it into a clean virtual environment, then run the report from Step 3 and pip check. If the report matches the file, your installed, locked, and runtime views agree.
Common errors when establishing versions
- Checking the wrong environment. The editor, the terminal, and the test runner each used a different interpreter. Print
sys.executablefrom inside the test run itself, for example with a short test, instead of from a separate shell. - Confusing import and distribution names.
version("yaml")raisesPackageNotFoundErroreven when PyYAML is installed. UsePyYAML, or look up the mapping withpackages_distributions(). - Trusting a stale
__version__. Use package metadata. - Editable installs. A package installed with
pip install -e .reports the version from its metadata at install time. If you changed the version in source afterwards, the metadata can be out of date until you reinstall. - Shadowed modules. A local file named
requests.pyorjson.pycan be imported instead of the real library. Printingrequests.__file__shows where the import came from. Treat any path outsidesite-packagesas a warning sign. - Containers and CI that differ from your laptop. The version on your machine is not the version in the build image. Run the same report inside the container or CI job.
Using the result
Once you have a report, you can do three things with it in the checks that follow in this tutorial:
- Look up documentation and the changelog for exactly that version, not for "latest".
- Include the report in prompts so the assistant is told which versions apply.
- Compare reports between environments to explain "works on my machine" failures.
Exercise
A teammate says an assistant's code using df.append(...) failed in CI, but passes on their laptop. Which three pieces of information would you collect first to explain the difference, and which commands would you use?
Show answer
Collect the interpreter path and Python version, the installed pandas version, and whether the environment matches the lock file. In each place (laptop and CI job) run a script that prints sys.executable, platform.python_version(), and importlib.metadata.version("pandas"), then run python -m pip check and compare python -m pip freeze output to the committed lock file. If CI has pandas 2.x and the laptop has 1.x, that explains the failure, because DataFrame.append was removed in pandas 2.0.
Exercise
Why does importlib.metadata.version("yaml") fail with PackageNotFoundError even though import yaml works, and how do you get the installed version starting from the import name?
Show answer
version() expects the distribution name that pip knows, which here is PyYAML, not the import name yaml. Call version("PyYAML"), or translate the import name with importlib.metadata.packages_distributions()["yaml"], which returns the distribution names (such as ["PyYAML"]) that provide that module, and pass the first one to version().