Sub topic 9
Verify suggested packages before installing them
This chapter assumes you can use pip, read a requirements.txt file, and run Python scripts in a virtual environment. It covers a failure that differs from an invented function. Here the assistant suggests a whole package that does not exist, or one whose name is close to a real package but is not the one you meant.
Why package names are a risk
An invented function fails when you run it, with an AttributeError or ImportError. An invented package can fail more quietly. If someone has registered the name on the public index, pip install succeeds and runs that person's code on your machine.
Three situations come up repeatedly:
- Nonexistent name. The assistant suggests
pip install fastjson-utils, and no such project exists. The install fails with "No matching distribution found". This is the harmless case. - Registered after the fact. The name did not exist, but an attacker saw that assistants suggest it and registered it with malicious code. Your install now works. This is sometimes called slopsquatting.
- Look-alike name. The name differs from the real package by a character or a suffix, such as
reqeustsforrequests. This is typosquatting, and it predates AI tools.
A related mistake is a mismatch between the import name and the install name. These are different things:
| You write in code | You install with pip |
|---|---|
| `import yaml` | `pip install pyyaml` |
| `import cv2` | `pip install opencv-python` |
| `import PIL` | `pip install pillow` |
| `import sklearn` | `pip install scikit-learn` |
An assistant that suggests pip install yaml or pip install sklearn may be pointing you at the wrong project. Never assume the two names match.
The verification flow
Each suggested package should pass four questions before it is installed. The flow below shows the order and where you stop.
Step 1: Does the name exist?
Ask the package index without installing anything. PyPI offers a JSON endpoint at https://pypi.org/pypi/<name>/json. A 404 means the project does not exist.
import json
import urllib.error
import urllib.request
def pypi_info(name):
"""Return the PyPI metadata for a project, or None if it does not exist."""
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
return json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
if __name__ == "__main__":
for candidate in ["requests", "definitely-not-a-real-package-xyz"]:
info = pypi_info(candidate)
print(candidate, "->", "missing" if info is None else info["info"]["version"])A missing project is a useful signal. It tells you the assistant invented the name, so ask what the real library for the task is, or search the index yourself.
An existing project is not proof of safety. Existence only rules out the first situation.
Step 2: Is it the project you intend?
Check the metadata that PyPI returns. Fields to read are the summary, the home page and source links, the author, and the license.
import json
import urllib.request
def summarize(name):
url = f"https://pypi.org/pypi/{name}/json"
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
info = data["info"]
print("name: ", info["name"])
print("version: ", info["version"])
print("summary: ", info["summary"])
print("home page: ", info.get("home_page") or info.get("project_urls"))
print("releases: ", len(data["releases"]))
summarize("requests")Compare what you find with what you expected:
- Does the source link point to the repository you know, or to an empty or unrelated one?
- Does the summary describe the task you have in mind?
- Does the name match the official documentation's install instructions exactly? Copy the command from the project's own documentation, not from the assistant.
Step 3: Is it maintained, with real history?
A legitimate project usually has several signals together. None is decisive alone.
| Signal | Reassuring | Suspicious |
|---|---|---|
| Release history | Many releases over months or years | One release, uploaded recently |
| Repository | Public, with commits, issues, and contributors | Missing, empty, or a link to someone else's project |
| Downloads and dependents | Used by other known projects | Almost no usage |
| Name | Matches the official docs | One character off from a popular name |
| Upload date | Predates the question you are asking | Created days ago |
The release dates are in the same JSON. This snippet prints the first and last upload times, which exposes a package that appeared very recently.
import json
import urllib.request
def release_span(name):
url = f"https://pypi.org/pypi/{name}/json"
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
times = [
f["upload_time_iso_8601"]
for files in data["releases"].values()
for f in files
]
if not times:
return None
return min(times), max(times), len(data["releases"])
print(release_span("requests"))A project with a single release uploaded last week, whose name matches a plausible assistant suggestion, deserves a hard look at its source before you proceed.
Step 4: Inspect without installing
You can download a package without installing it and read its contents first.
pip download --no-deps --no-binary :all: --dest ./inspect requestsThis fetches the source distribution into ./inspect. Unpack it and look for the following:
- A
setup.pythat runs network calls, reads environment variables, or executes encoded strings. - Install-time hooks that do more than build the package.
- Code that has no relationship to the stated purpose.
Be aware that building a source distribution can itself run code, so unpack the archive and read it. Do not build it. For a quick check on a wheel, which is a zip file, list its contents:
pip download --no-deps --only-binary :all: --dest ./inspect requests
python -m zipfile -l ./inspect/*.whlStep 5: Pin and verify what you install
After you decide to use a package, record exactly which release you approved. Pinning prevents a later, different upload from replacing it silently.
requests==2.32.3For stronger protection, use hash checking. Generate a requirements file with hashes using pip-tools, then require them at install time.
pip install pip-tools
pip-compile --generate-hashes requirements.in -o requirements.txt
pip install --require-hashes -r requirements.txtWith --require-hashes, pip refuses any file whose hash differs from the recorded one. If the same name and version were swapped for a modified file, the install fails.
Version context from an earlier chapter also applies here. Confirm the installed version with importlib.metadata, because the version you pinned determines which documentation applies.
from importlib.metadata import PackageNotFoundError, version
for name in ["requests", "not-installed-package"]:
try:
print(name, version(name))
except PackageNotFoundError:
print(name, "is not installed")Step 6: Check for a name collision with your own configuration
Some environments use more than one index, such as a private company index plus PyPI. This setup creates dependency confusion. If a package name exists on both, the installer may choose the public one with a higher version number.
- Prefer
--index-urlwith a single trusted index over--extra-index-url, which merges indexes. - Reserve your internal package names on the public index, or use a tool that scopes names to specific indexes.
- Review any assistant-written change to
pip.conf,requirements.txt, orpyproject.tomlthat adds an index URL.
Reviewing a suggestion in practice
Suppose an assistant writes this in a pull request:
pip install fastxml-parserWork through the checks in order:
- Query
https://pypi.org/pypi/fastxml-parser/json. If it returns 404, reject the suggestion and ask for a library that is documented to parse XML. The standard library already includesxml.etree.ElementTree, andlxmlis a well-known alternative. - If it exists, read the summary and source link. If the repository is missing or unrelated, reject it.
- Check the release history. A single release from last week is a warning.
- If everything passes, pin the exact version, and add hashes if your project uses them.
Often the best outcome is that you replace the suggestion with a dependency you already have or a standard library module. Fewer dependencies means fewer names to verify.
Add a guard in CI
Manual vetting does not scale. A short script can enforce part of the policy by failing when a requirement is not pinned or does not exist.
import json
import re
import sys
import urllib.error
import urllib.request
PIN = re.compile(r"^([A-Za-z0-9._-]+)==([^\s;#]+)")
def exists(name, ver):
url = f"https://pypi.org/pypi/{name}/{ver}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
json.load(resp)
return True
except urllib.error.HTTPError as err:
if err.code == 404:
return False
raise
def main(path):
failures = []
with open(path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith(("#", "-")):
continue
match = PIN.match(line)
if not match:
failures.append(f"not pinned with ==: {line}")
elif not exists(*match.groups()):
failures.append(f"not found on PyPI: {line}")
for failure in failures:
print(failure)
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "requirements.txt"))Run it as a CI step against the requirements file. It catches invented names and unpinned entries. It does not judge whether an existing package is trustworthy, so keep a human review for new dependencies.
Common errors
- Trusting an install command because it looks like a normal command.
- Assuming the import name and the PyPI name are the same.
- Treating "pip install succeeded" as proof that the package is legitimate.
- Adding
--extra-index-urlto silence a "not found" error. - Leaving a new dependency unpinned.
Exercise
An assistant tells you to run pip install sklearn-utils-pro for a data-cleaning task. The PyPI JSON lookup returns a project with one release, uploaded five days ago, whose repository link is empty. List the checks you applied, what they show, and what you do next.
Show answer
The name exists, so it passes the existence check, but that only rules out a plain invented name. The metadata fails the intent check because the source link is empty, so you cannot confirm what the project is. The release history fails the maintenance check because there is a single, very recent release with no track record. Together these resemble a package registered after assistants began suggesting the name. Do not install it. Look for an established library for the task, such as scikit-learn's own preprocessing tools or pandas, copy the install command from that project's documentation, and pin the version you choose.
Exercise
Why is pip install --require-hashes useful after you have already pinned requests==2.32.3?
Show answer
A version pin names a release but does not prove which file you receive. If a file under that name and version were replaced or tampered with, a plain pinned install would accept it. With --require-hashes, pip compares the downloaded file to the hash you recorded and refuses the install if they differ.