Thuta Learning
Python
AdvancedProgrammingBeginner

Package Management

PythonLesson 5430 min

What you'll walk away with

  • Use python -m pip to install, upgrade, uninstall, list and show packages
  • Read which versions the ==, >=,< and ~= specifiers allow
  • Tell direct from transitive dependencies and explain what pip freeze records
  • Reinstall a project into a fresh environment from requirements.txt
  • Check an installed version from code with importlib.metadata

Explain it simply

pip in plain language

pip is Python's package manager. It downloads libraries other people wrote, such as requests, pandas or Django, from an online library called the Python Package Index (PyPI) and installs them into your environment. When a package needs other packages, pip finds and installs those too.

Think of a recipe. requirements.txt is the shopping list and pip is the person who goes shopping. If the list just says 'eggs', you may come home with a different size every trip, and if you do not state versions, every install may bring home a different version.

Problem → Why → Solution

The problem: installs with no versions

Your requirements.txt lists django and requests with no versions, and it works fine for six months. Then you deploy to a new server, pip fetches the newest major version, and the app no longer starts because an API it used was removed. You did not change a single line of code, yet finding what changed is hard, because there is no record of which versions used to work.

requirements.txt
django
requests
# no versions: each fresh install takes whatever is newest that day

What specifiers and snapshots fix

A range such as Django>=5.2,<6.0 allows bug-fix releases but blocks the next major version, which may contain breaking changes. pip freeze records the exact versions that are really in the environment, so you can rebuild the exact set of packages you tested in production. 'What changed?' then becomes a simple comparison of two files.

Core concept: specifiers, the dependency tree and freeze

Call pip as python -m pip, so it installs into the python that is running, for example your activated venv. python -m pip install requests looks up requests on PyPI, also finds what it needs, certifi, idna, urllib3 and charset-normalizer, resolves versions that all fit together and installs them. A package you ask for yourself, like requests, is a direct dependency; the ones pulled in because of it are transitive dependencies.

SpecifierAllows
requests==2.32.3exactly 2.32.3 (a pin)
Django>=5.2,<6.05.2 or newer but below 6.0 (5.x only)
requests~=2.32compatible release: >=2.32 and ==2.*
requestsany version (takes the newest)

python -m pip freeze prints every installed package in the environment as name==version, including transitive dependencies and test tools. It is a snapshot of 'what is in this environment today', not a list of 'what the project needs'. That is why many teams keep two files: one with the direct dependencies as ranges (pyproject.toml or requirements.in), and a lock file with everything pinned.

Package names ignore case and separators: Django and django, or python_dotenv and python-dotenv, are the same package, because pip normalises names to lowercase with dashes before comparing them. python -m pip show requests prints its version, Requires (what it needs) and Required-by (what needs it), which helps when you wonder why a package is installed at all.

Installing with --upgrade takes the highest version the specifier allows, while uninstall removes only the named package and leaves behind the dependencies it brought in. Over time an environment therefore collects packages nobody needs, and deleting the venv and rebuilding it from the lock file is the cleanest reset.

List, resolve, snapshot
  1. Write direct deps with ranges
  2. pip resolves the dependency tree
  3. Install everything into the env
  4. freeze records exact versions

The range file says what is allowed; the freeze or lock file says what was actually tested. You need both.

General pattern

bash
python -m pip install <package>                 # newest allowed version
python -m pip install "<package>>=X.Y,<Z.0"     # a bounded range (quote it)
python -m pip install --upgrade <package>
python -m pip uninstall <package>
python -m pip show <package>                    # version, Requires, Required-by
python -m pip freeze > requirements.txt         # snapshot of this environment
python -m pip install -r requirements.txt       # rebuild elsewhere

Start every command with python -m pip. Quote any specifier containing > or <, because the shell would otherwise treat those characters as redirection.

Worked example: auditing a requirements file

Rather than just listing pip commands, this script reads requirements.txt text line by line, skips comments, normalises each package name the way pip does, and classifies every line as a pin, a range or unpinned.

At the end it calls importlib.metadata.version() with a name that is not installed and catches PackageNotFoundError. Installed versions differ between machines, so this choice keeps the output identical everywhere.

audit_requirements.py
import re
from importlib import metadata

REQUIREMENTS = """\
# web app dependencies
Django>=5.2,<6.0
requests==2.32.3
python_dotenv
"""


def parse_line(line):
    line = line.split("#", 1)[0].strip()
    if not line:
        return None
    match = re.match(r"([A-Za-z0-9._-]+)\s*(.*)", line)
    name, spec = match.group(1), match.group(2)
    canonical = re.sub(r"[-_.]+", "-", name).lower()
    return canonical, spec


for raw in REQUIREMENTS.splitlines():
    parsed = parse_line(raw)
    if parsed is None:
        continue
    name, spec = parsed
    if spec.startswith("=="):
        kind = "pinned"
    elif spec:
        kind = "range"
    else:
        kind = "unpinned (any version)"
    print(f"{name:<14} {spec or '-':<12} {kind}")

try:
    metadata.version("surely-not-installed-demo-pkg")
except metadata.PackageNotFoundError:
    print("surely-not-installed-demo-pkg: not installed in this environment")

Code breakdown

  1. Drop comments and blanks line = line.split("#", 1)[0].strip()

    Cuts off everything after # and strips spaces. If nothing remains, the function returns None, so comment lines and blank lines are skipped.

  2. Split name from specifier match = re.match(r"([A-Za-z0-9._-]+)\s*(.*)", line)

    The first group captures the characters allowed in a package name, and the second captures the rest of the line, the specifier, such as >=5.2,<6.0.

  3. Normalise like pip canonical = re.sub(r"[-_.]+", "-", name).lower()

    Runs of -, _ and . become a single - and everything is lowercased, so Django becomes django and python_dotenv becomes python-dotenv.

  4. Classify the line if spec.startswith("=="):

    A spec starting with == pins one version; any other specifier is a range; no specifier at all means unpinned, so every install takes the newest version.

  5. Ask what is installedexcept metadata.PackageNotFoundError:

    metadata.version(name) returns the version string when the package is installed and raises PackageNotFoundError when it is not; this is the standard way to check a dependency from code.

You should see
django         >=5.2,<6.0   range
requests       ==2.32.3     pinned
python-dotenv  -            unpinned (any version)
surely-not-installed-demo-pkg: not installed in this environment

Pairing a range file with a lock file

Projects commonly keep two files. requirements.in (or the dependencies in pyproject.toml) lists the direct dependencies as ranges, written by hand, and a tool such as pip-tools' pip-compile generates the lock file with exact versions. When the lock file is regenerated, its diff shows exactly what was upgraded.

requirements.in
# direct dependencies only, as ranges
Django>=5.2,<6.0
requests~=2.32
bash
python -m pip install pip-tools
pip-compile requirements.in -o requirements.txt   # pins every package, with comments
python -m pip install -r requirements.txt         # same versions everywhere
python -m pip check                               # verify installed deps are compatible

The externally-managed-environment error

On systems such as Debian, Ubuntu or Homebrew, the OS manages Python, so a global pip install can fail with an 'externally-managed-environment' error. It protects the system's own tools. The fix is not sudo pip but creating a venv and installing inside it.

In real projects

pip in real projects

In production projects, updating dependencies is a process rather than something done whenever someone remembers. The lock file lives in git, updates arrive as pull requests, and CI installs them into a fresh environment and runs the tests. Only green builds get merged, so production never receives a version nobody has tested.

  • Bots such as Dependabot or Renovate open a pull request that updates the lock file whenever a new version is released.
  • A tool such as pip-audit checks the installed versions against a database of known vulnerabilities and usually runs in CI.
  • Docker images copy requirements.txt and install it before copying the application code, so a code-only change reuses the cached dependency layer.
  • Companies point --index-url at a private package index, such as an internal mirror, so installs come only from trusted sources.

Common mistakes

Common mistakes with pip

Using raw pip freeze as the dependency list

Tools you installed while experimenting, such as jupyter or black, and transitive packages whose origin nobody remembers all end up in the freeze output. Later, when you want to drop a package, you cannot tell which ones are really needed. Keep direct dependencies in their own file and generate the lock file with a tool.

Using sudo pip, or the wrong pip

sudo pip install can overwrite the operating system's Python packages and break system tools. A bare pip command may also install into a different interpreter from python, depending on PATH. Use python -m pip inside a venv.

Mistyping a package name

PyPI has seen malicious packages whose names differ from popular ones by a single letter (typosquatting). A typo like requets can run an attacker's code during installation. Check the name on the PyPI page before installing, and review lock file changes.

Mini challenge

Mini challenge: compare two freeze files

Take two pip freeze outputs, before and after an update, and print a report of which packages were added, which were removed and which changed version. Flag any package whose version went down as DOWNGRADED.

  • parse_freeze(text) turns name==version lines into a {name: version} dict with lowercased names
  • version_key(version) turns "5.2.1" into the tuple (5, 2, 1)
  • diff_freezes(old, new) returns lines starting with +, - or ~, sorted by name
  • Leave unchanged packages out of the report
freeze_diff.py
OLD_FREEZE = """\
asgiref==3.8.1
chardet==5.2.0
Django==5.1.4
requests==2.32.3
sqlparse==0.5.1
"""

NEW_FREEZE = """\
asgiref==3.8.1
Django==5.2.1
requests==2.31.0
sqlparse==0.5.1
whitenoise==6.8.2
"""


def parse_freeze(text):
    # TODO: {lowercased name: version} for every "name==version" line
    ...


def version_key(version):
    # TODO: "5.2.1" -> (5, 2, 1) so versions compare numerically
    ...


def diff_freezes(old, new):
    # TODO: "+ name ver (added)", "- name ver (removed)",
    #       "~ name old -> new (upgraded/DOWNGRADED)"; skip unchanged
    ...


# TODO: print each line of the report

Expected: Four lines: chardet removed, django 5.1.4 -> 5.2.1 upgraded, requests 2.32.3 -> 2.31.0 DOWNGRADED and whitenoise added; asgiref and sqlparse do not appear.

Show hint

old.keys() | new.keys() gives the set of all names; sort it with sorted(). Comparing as strings would make "5.10" < "5.9", which is why you compare tuples of ints. If you must handle pre-releases such as 2.0rc1, real projects use packaging.version.Version.

Show solution
freeze_diff.py
OLD_FREEZE = """\
asgiref==3.8.1
chardet==5.2.0
Django==5.1.4
requests==2.32.3
sqlparse==0.5.1
"""

NEW_FREEZE = """\
asgiref==3.8.1
Django==5.2.1
requests==2.31.0
sqlparse==0.5.1
whitenoise==6.8.2
"""


def parse_freeze(text):
    pins = {}
    for line in text.splitlines():
        line = line.strip()
        if line and not line.startswith("#") and "==" in line:
            name, version = line.split("==", 1)
            pins[name.lower()] = version
    return pins


def version_key(version):
    return tuple(int(part) for part in version.split("."))


def diff_freezes(old, new):
    changes = []
    for name in sorted(old.keys() | new.keys()):
        before, after = old.get(name), new.get(name)
        if before is None:
            changes.append(f"+ {name} {after} (added)")
        elif after is None:
            changes.append(f"- {name} {before} (removed)")
        elif before != after:
            newer = version_key(after) > version_key(before)
            changes.append(f"~ {name} {before} -> {after} "
                           f"({'upgraded' if newer else 'DOWNGRADED'})")
    return changes


for change in diff_freezes(parse_freeze(OLD_FREEZE), parse_freeze(NEW_FREEZE)):
    print(change)

Quick quiz 1 / 3

requirements.txt says Django>=5.2,<6.0. Which of these versions may pip install?

Quick quiz 2 / 3

In a fresh venv you ran only python -m pip install requests. What does pip freeze show?

Quick quiz 3 / 3

On Ubuntu, pip install requests fails with 'externally-managed-environment'. What should you do?

What to remember

  • Call pip as python -m pip and install inside a venv.
  • == pins, >=,< is a range, ~= is a compatible release, and no specifier takes the newest version.
  • pip resolves and installs transitive dependencies too, and pip freeze is a snapshot of the whole environment.
  • Keep direct dependencies as ranges in one file and exact versions in a lock file, and rebuild with -r.
  • importlib.metadata.version() checks an installed version from code.

Python Documentation — Virtual Environments and Packages — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Package Management | Thuta Learning