Module 9.3

Third-Party Libraries

PyPI has over 400,000 packages to supercharge your projects. Instead of writing everything from scratch, you can install packages for web frameworks, data science, machine learning, automation, and more. pip is your tool for discovering and installing these packages.

45 min
Intermediate
Hands-on
What You'll Learn
  • Using pip
  • Virtual environments
  • requirements.txt
  • Popular packages
  • Best practices
Contents
01

What is PyPI?

PyPI (Python Package Index) is the official repository for third-party Python packages. It hosts over 400,000 projects that you can install with a single command. From web frameworks like Django and Flask to data science tools like pandas and NumPy, PyPI has it all.

Key Concept

The pip Workflow

pip is the package installer for Python. It downloads packages from PyPI and installs them on your system. You search for packages, install them with pip, import them in your code, and use their functionality.

Remember: pip comes pre-installed with Python 3.4 and later. No separate installation needed.

The pip Workflow

From discovery to implementation in 4 simple steps

1
SEARCH
pypi.org Browse packages at pypi.org/project/<name>
2
INSTALL
pip install package Download and install from PyPI
3
IMPORT
import package Load package into your script
4
USE
package.function() Call functions and use features
Real Example: Installing Requests
pypi.org/project/requests
pip install requests
import requests
requests.get(url)

Popular Third-Party Packages

Category Package Purpose
WebrequestsHTTP requests made simple
Webflask, djangoWeb frameworks
DatapandasData manipulation and analysis
DatanumpyNumerical computing
VisualizationmatplotlibPlotting and charts
MLscikit-learnMachine learning
TestingpytestTesting framework
AutomationseleniumBrowser automation
02

Using pip

pip is a command-line tool that manages Python packages. You can install, uninstall, upgrade, and list packages. All commands run in your terminal or command prompt.

Installing Packages

# Install a package
pip install requests

# Install a specific version
pip install requests==2.28.0

# Install minimum version
pip install "requests>=2.25.0"

# Install multiple packages
pip install requests flask pandas

# Upgrade a package
pip install --upgrade requests

Use == for exact version, >= for minimum. Quotes may be needed to escape special characters in your shell.

Managing Packages

# List installed packages
pip list

# Show package details
pip show requests

# Uninstall a package
pip uninstall requests

# Check for outdated packages
pip list --outdated

# Search is deprecated - use pypi.org instead
# pip search no longer works

pip show displays version, location, dependencies, and homepage. Use pip list --outdated to find packages that need updates.

Using Installed Packages

# After: pip install requests
import requests

# Make a GET request
response = requests.get("https://api.github.com")
print(response.status_code)  # 200
print(response.json())       # API response as dict

# After: pip install rich
from rich import print
print("[bold red]Hello[/bold red] World!")

Once installed, import packages like any other module. Read their documentation to learn the API.

Practice: pip

Task: Install requests and write code to fetch a JSON API response.

Show Solution
# In terminal:
pip install requests
# In Python:
import requests

url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(url)
data = response.json()
print(f"Title: {data['title']}")

Task: Write the pip commands to list all packages and show details of one.

Show Solution
# List all installed packages
pip list

# Show details of a specific package
pip show requests

# Check for outdated packages
pip list --outdated

Task: Write pip commands to install Flask 2.0.0 exactly, then upgrade it to latest.

Show Solution
# Install exact version
pip install flask==2.0.0

# Check installed version
pip show flask

# Upgrade to latest
pip install --upgrade flask

# Verify upgrade
pip show flask
03

Virtual Environments

Virtual environments isolate project dependencies. Each project can have its own packages and versions without conflicts. This is essential for professional Python development. Never install packages globally for projects.

Isolation

Each project has its own packages. No conflicts between projects.

Version Control

Different projects can use different package versions.

Reproducibility

Export and share exact dependencies with requirements.txt.

Clean System

Keep your global Python clean. Delete venv to remove all packages.

Creating Virtual Environments

# Create a virtual environment
python -m venv myenv

# Folder structure created:
# myenv/
#   bin/       (Linux/Mac) or Scripts/ (Windows)
#   lib/       Installed packages go here
#   include/   C headers (if needed)
#   pyvenv.cfg Configuration file

The venv module comes with Python. "myenv" is the name of your environment folder. Common names: venv, .venv, env.

Activating and Deactivating

# Windows (Command Prompt)
myenv\Scripts\activate

# Windows (PowerShell)
myenv\Scripts\Activate.ps1

# Linux/Mac
source myenv/bin/activate

# Your prompt changes: (myenv) user@host:~$
# Now pip installs to the virtual environment

# Deactivate when done
deactivate

When activated, (myenv) appears in your prompt. All pip commands now affect only this environment.

Complete Workflow

# Start a new project
mkdir my_project
cd my_project

# Create and activate environment
python -m venv venv
venv\Scripts\activate    # Windows

# Install packages (only in this env)
pip install requests flask

# Work on your project...
# When done:
deactivate

Always create a venv for each project. Add venv/ to .gitignore since it should not be in version control.

Practice: Virtual Environments

Task: Create a virtual environment called "test_env" and activate it.

Show Solution
# Create the environment
python -m venv test_env

# Activate (Windows)
test_env\Scripts\activate

# Activate (Linux/Mac)
source test_env/bin/activate

# Verify - should show test_env location
pip --version

Task: Write the complete commands to start a new project with a venv and install pandas.

Show Solution
# Create project folder
mkdir data_project
cd data_project

# Create virtual environment
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Install pandas
pip install pandas

# Verify installation
pip list

Task: Deactivate a venv, delete it, and create a fresh one.

Show Solution
# Deactivate first (if active)
deactivate

# Delete the environment folder (Windows)
rmdir /s /q venv

# Delete (Linux/Mac)
rm -rf venv

# Create fresh environment
python -m venv venv

# Activate and reinstall from requirements.txt
venv\Scripts\activate
pip install -r requirements.txt
04

requirements.txt

requirements.txt is a file that lists all packages your project needs. It allows others (or yourself on another machine) to recreate your exact environment. This file should be committed to version control.

Creating requirements.txt

# Generate from installed packages
pip freeze > requirements.txt

# The file looks like:
# requests==2.28.0
# flask==2.3.0
# pandas==2.0.0
# numpy==1.24.0

pip freeze outputs all installed packages with exact versions. The > redirects output to a file.

Installing from requirements.txt

# Clone a project from Git
git clone https://github.com/user/project.git
cd project

# Create virtual environment
python -m venv venv
venv\Scripts\activate     # Windows

# Install all dependencies
pip install -r requirements.txt

# Now you have the exact same packages!

The -r flag tells pip to read from a file. This installs everything listed in requirements.txt.

Manual requirements.txt

# requirements.txt - Manual version
# You can add comments with #

# Core dependencies
requests>=2.25.0
flask>=2.0,<3.0

# Data processing
pandas==2.0.0
numpy

# Development only
pytest
black

You can write requirements.txt manually with version ranges. Use >= for minimum, == for exact, < for maximum.

Practice: requirements.txt

Task: Install 2 packages and generate a requirements.txt file.

Show Solution
# Install some packages
pip install requests colorama

# Generate requirements file
pip freeze > requirements.txt

# View the file
cat requirements.txt  # Linux/Mac
type requirements.txt # Windows

Task: Write a requirements.txt that requires Flask 2.x and requests 2.25 or higher.

Show Solution
# requirements.txt
# Web framework - version 2.x only
flask>=2.0,<3.0

# HTTP library - 2.25 or higher
requests>=2.25.0

# Optional: with comments for clarity
# gunicorn for production server
gunicorn>=20.0

Task: Write a complete setup script that creates venv, installs from requirements.txt, and runs the app.

Show Solution
# setup.bat (Windows) or setup.sh (Linux/Mac)

# Create virtual environment
python -m venv venv

# Activate (modify for your OS)
call venv\Scripts\activate

# Upgrade pip first
pip install --upgrade pip

# Install dependencies
pip install -r requirements.txt

# Run the application
python app.py

Key Takeaways

PyPI is Huge

Over 400,000 packages. Check pypi.org before writing code yourself.

pip is Your Tool

pip install, pip list, pip show, pip freeze. Learn these commands well.

Always Use venv

Virtual environments prevent conflicts. One venv per project, always.

requirements.txt

Track dependencies. pip freeze > requirements.txt saves your setup.

Version Control

Commit requirements.txt, not the venv folder. Add venv/ to .gitignore.

Read Documentation

Every package has docs. Read them to learn the API before using.

Knowledge Check

Quick Quiz

Test what you've learned about pip and virtual environments

1 What command installs a package from PyPI?
2 What does "python -m venv myenv" do?
3 What command generates a requirements.txt file?
4 What should you add to .gitignore?
5 What does pip install -r requirements.txt do?
6 Why should you use virtual environments?
Answer all questions to check your score