Skip to content

Module 14 · Python Modules and Packages — topic 9 of 13

Installing packages

Getting third-party packages from PyPI: what PyPI is, installing with python -m pip, choosing versions, checking whether a package is available, and handling optional dependencies in code.

Beginner 8 min read·Lesson 217 of 306 in Python Programming

Learning objectives

  • Install, upgrade and uninstall packages
  • Check whether a package is importable
  • Handle optional dependencies gracefully

Definition

Third-party packages are libraries published by the community, mostly on the Python Package Index (PyPI). They are installed with pip into the active Python environment, after which they can be imported like standard modules.

Introduction

The standard library is large, but PyPI hosts hundreds of thousands more packages: web frameworks, data tools, game engines and API clients.

Why it matters

Knowing how to install packages correctly — into the right environment, at the right version — avoids the classic 'it works on my machine' problems.

Detailed explanation

PyPI (pypi.org) is the main public repository of Python packages.

Install with python -m pip install package. Using python -m pip guarantees pip installs into the same Python you run.

Install a specific version with package==1.2.3, or a range with >= and <. Upgrade with --upgrade; remove with pip uninstall.

Packages are installed into a site-packages folder of the active environment. Installing into a virtual environment (see later) keeps projects separate.

The import name can differ from the install name: pip install beautifulsoup4 is imported as bs4, pip install pillow as PIL.

Code can check for a package with importlib.util.find_spec(name) or by catching ImportError, and fall back when an optional dependency is missing.

Only install packages you trust: check the exact name (typo-squatting is real), the project page and its maintainers.

Syntax

Terminal
python -m pip install requests
python -m pip install "requests==2.32.3"
python -m pip install --upgrade requests
python -m pip uninstall requests
  • Use python -m pip.
  • Pin versions when needed.
  • Install into a virtual environment.

Code examples

Installing from the command line

Terminal
python -m pip install requests
python -m pip install "rich>=13"
python -m pip install --upgrade requests

Run these in a terminal, not inside Python. They download packages from PyPI.

Is a module available?

Python
import importlib.util
for name in ["json", "surely_not_installed_pkg"]:
print(name, importlib.util.find_spec(name) is not None)
Output
json True
surely_not_installed_pkg False

More examples

An optional dependency

Python
import json
try:
import yaml_not_installed_example as yaml
HAVE_YAML = True
except ImportError:
HAVE_YAML = False
def load_config(text):
if HAVE_YAML:
return yaml.safe_load(text)
return json.loads(text)
print(HAVE_YAML, load_config('{"debug": false}'))
Output
False {'debug': False}

Step-by-step explanation

  • The import is attempted once at module load.
  • If the optional package is missing, a flag records that and JSON is used instead.
  • The program works either way, with extra features when the package is installed.

Expected output

Running “An optional dependency” prints exactly:

TextOutput
False {'debug': False}

Practical applications

  • pip install requests for HTTP, pandas for data analysis, flask for web apps.
  • Libraries offering extra features when optional packages are present.

Best practices

  • Install into a virtual environment.
  • Check package names and reputations.
  • Record dependencies in requirements.txt or pyproject.toml.

Common mistakes

Plain pip on a multi-Python machine

Avoid

pip install requests # may target another Python

Prefer

python -m pip install requests

python -m pip installs into the interpreter you actually run.

Installing with sudo

Avoid

sudo pip install package

Prefer

Use a virtual environment.

System-wide installs can break the operating system's own Python tools.

Important notes

  • Newer tools such as uv offer faster installs, but pip remains the standard.

Key takeaways

  • PyPI hosts third-party packages.
  • Install with python -m pip install.
  • Handle optional imports with try/except ImportError.

Try it yourself

  1. 1
    Write code that prints a friendly installation hint if a package cannot be imported.
  2. 2
    Find the import names for the PyPI packages pillow, beautifulsoup4 and python-dateutil.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions cover the “Python Modules and Packages” module. Answers and explanations are revealed after you submit.

  • ModerateWhat happens the second time a module is imported in the same program?
  • ModerateCode under if __name__ == "__main__": runs when…
  • ModerateWhat is printed?
Practise this module