Intermediate   Chapter 92 · 25 min read · Module 7: Python Modules and Packages

pip Package Manager

Learning objectives
  • After this chapter you can explain what pip and PyPI are.
  • You can write the common pip commands to install, upgrade, show, list, freeze and uninstall packages.
  • You can read and write a requirements.txt file with version specifiers.
  • You can run pip safely through python -m pip so that it matches the right Python.
  • You can check from Python code whether a package can be imported or is installed.

Python comes with a large standard library, but the real power of the ecosystem is the huge number of packages written by other people. There are packages for data analysis, web servers, images, testing and thousands of other jobs. The tool that installs these packages is called pip.

pip downloads packages from the Python Package Index, known as PyPI, and puts them where your Python can find them. It also works out which other packages a package needs, which are called its dependencies, and installs those as well. With one short command you can add a library to your project.

This chapter teaches the commands you will use every day, the format of a requirements file, and the version rules that stop projects from breaking. Because installing needs a network, the pip commands are shown as text, while the runnable examples show how to read requirement lines and check packages with plain Python code.

What are pip and PyPI?

pip: the standard tool for installing and managing Python packages; its name is often explained as 'Pip Installs Packages'

PyPI is the public website and server that stores packages. When you ask pip for a package called requests, pip looks it up on PyPI, finds a version that fits your Python, downloads it and installs it. pip is included with Python from version 3.4 onward, so you normally do not have to install it yourself.

The safest way to run pip is as a module of the exact Python you want to use: python -m pip. On some systems there are several Pythons installed, and a plain pip command might belong to a different one. Writing python -m pip removes this doubt, because it always uses the pip of that interpreter. On many systems the command is python3 -m pip, and on Windows you can also use py -m pip.

The everyday commands

TaskCommand
Check the pip versionpython -m pip --version
Install a packagepython -m pip install requests
Install a fixed versionpython -m pip install requests==2.31.0
Upgrade a packagepython -m pip install --upgrade requests
Show details of a packagepython -m pip show requests
List installed packagespython -m pip list
Save installed packagespython -m pip freeze > requirements.txt
Install from a filepython -m pip install -r requirements.txt
Remove a packagepython -m pip uninstall requests
Example 1: a typical pip session (shown, not executed)
python -m pip install requests
python -m pip show requests
python -m pip uninstall requests
Successfully installed requests-2.31.0 Name: requests Version: 2.31.0 Successfully uninstalled requests-2.31.0

The output above is only an example, because it needs the internet and the version numbers change over time. The commands are typed in a terminal, not inside the Python prompt. This is a common point of confusion for beginners who type pip install in the interactive shell and get a SyntaxError.

Version specifiers

A package name can be followed by a rule that limits which versions are allowed. These rules keep your project working when a new release changes behaviour.

SpecifierMeaning
requests==2.31.0exactly this version
requests>=2.0this version or newer
requests>=2.0,<3.0newer than 2.0 but below 3.0
requests~=2.31compatible release: 2.31 or newer but below 3.0
requests!=2.30.0any version except this one

Versions are compared number by number, not as plain text. Version 2.10 is newer than 2.9, even though the text '2.10' sorts before '2.9'. pip uses the same idea, and the example below shows it with tuples of integers.

Example 2: comparing version numbers
def as_tuple(version):
    return tuple(int(part) for part in version.split("."))

print("2.10" > "2.9")
print(as_tuple("2.10") > as_tuple("2.9"))
print(as_tuple("2.31.0") >= as_tuple("2.0"))
print(sorted(["1.10", "1.2", "1.9"], key=as_tuple))
False True True ['1.2', '1.9', '1.10']

The first line prints False because text is compared character by character, while the second prints True because the numbers are compared. This is why you should never sort versions as strings.

Requirements files

A requirements file is a plain text file, normally named requirements.txt, with one package rule per line. Blank lines are ignored and a line that starts with # is a comment. Teams share this file so that everyone installs the same packages, and pip install -r requirements.txt installs them all at once. The example below reads such a file with a small parser.

Example 3: reading a requirements file
import re

text = """# web tools
requests==2.31.0
flask>=2.0,<3.0

rich
"""

def parse(line):
    match = re.match(r"([A-Za-z0-9_.-]+)(.*)", line)
    return match.group(1), match.group(2) or "any version"

for line in text.splitlines():
    line = line.strip()
    if not line or line.startswith("#"):
        continue
    name, rule = parse(line)
    print(f"{name:10} {rule}")
requests ==2.31.0 flask >=2.0,<3.0 rich any version

Each printed row shows the package name and the rule. The command pip freeze writes the exact installed versions in this same format, which is useful for repeatable setups. Use a looser file for what your project needs and a frozen file for exact deployment.

Checking packages from Python

Sometimes a program should check whether a package is available before using it. The function importlib.util.find_spec returns None when a module cannot be found. The module importlib.metadata reads the installed version of a distribution, and raises PackageNotFoundError when it is missing. Remember that the name you install with pip (the distribution name) can differ from the name you import. For example you install beautifulsoup4 but import bs4.

Example 4: is a package available?
import importlib.util
from importlib import metadata

print(importlib.util.find_spec("json") is not None)
print(importlib.util.find_spec("no_such_package_xyz") is None)

try:
    metadata.version("no-such-package-xyz")
except metadata.PackageNotFoundError:
    print("not installed")
True True not installed
Be careful with what you install. Anyone can upload to PyPI, so check the package name for typing mistakes, read its page, and prefer well-known, maintained projects.

Building a pip command in code

Programs that automate setup can call pip through the subprocess module. Using sys.executable makes the command run with the same Python as the program. The example only builds the list of arguments and does not run it, so it needs no network.

Example 5: the arguments of a pip call
import sys

cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "requests"]
print(cmd[1:])
print(" ".join(cmd[1:]))
['-m', 'pip', 'install', '--upgrade', 'requests'] -m pip install --upgrade requests

Python syntax

Syntax
python -m pip install package
Syntax
python -m pip install package==1.2.3
Syntax
python -m pip install -r requirements.txt
Syntax
python -m pip freeze > requirements.txt
Syntax
python -m pip uninstall package

Real-world applications

  • Adding libraries such as requests, flask or pandas to a project.
  • Sharing the exact list of needed packages with a team using requirements.txt.
  • Rebuilding the same environment on a new computer or a server.
  • Upgrading a package to receive security fixes.
  • Removing packages that a project no longer uses.

Common mistakes

Mistake: Typing pip install inside the Python prompt (>>>).
Fix: Run pip commands in the terminal or command prompt, not in the Python interpreter.
Mistake: Using pip that belongs to a different Python than the one that runs your program.
Fix: Use python -m pip install ... so that both use the same interpreter.
Mistake: Installing everything globally, which mixes versions of different projects.
Fix: Use a virtual environment for each project (see the next chapter).
Mistake: Comparing version numbers as strings.
Fix: Compare them as tuples of integers, or use the packaging library.
Mistake: Installing a package with a misspelled name that belongs to someone else.
Fix: Check the exact name and the project page on PyPI before you install.

Important tips

  • Pin important versions in requirements.txt so builds are repeatable.
  • Run python -m pip list --outdated to see which packages have newer versions.
  • Update pip itself with python -m pip install --upgrade pip.
  • Use python -m pip show name to find where a package is installed and what it needs.

Key points summary

  • pip installs packages from PyPI and also installs their dependencies.
  • Run it as python -m pip to match the right interpreter.
  • requirements.txt lists packages, one per line, with optional version rules.
  • == means exact version, >= means at least, ~= means compatible release.
  • Distribution names and import names can differ.

Exam and interview points

  • pip is the standard Python package installer; PyPI is the package index.
  • pip install -r file installs every requirement in a file.
  • pip freeze outputs name==version lines.
  • == pins a version; ~= allows compatible updates.
  • python -m pip is the safest way to call pip.

Quick revision

  • pip + PyPI = install packages.
  • python -m pip install name.
  • pip list, pip show, pip freeze, pip uninstall.
  • requirements.txt = one rule per line.
  • Versions compare as numbers, not text.
  • Use a virtual environment for every project.

Frequently asked questions

What is the difference between pip and PyPI?

PyPI is the online store of packages. pip is the tool on your computer that downloads from it and installs packages.

Why does pip say 'command not found'?

The pip program may not be on your PATH. Try python -m pip instead, which finds pip through the Python itself.

What does pip freeze do?

It prints every installed package with its exact version, in requirements format. Redirect it to a file to save it.

How do I install a specific version?

Add == and the version, for example python -m pip install requests==2.31.0.

Is it safe to install any package?

Not always. Packages can be wrong, abandoned or even harmful. Install packages from trusted projects and check the name carefully.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters