intermediate

Pip & Virtual Environments

6 min readLast updated: 2026-07-12

Overview

Isolate project dependencies using virtual environments and manage external libraries using pip.

Learning Objectives

  • Create and activate virtual environments using venv.
  • Install third-party libraries using pip.
  • Manage dependencies lists using requirements.txt.

Concept Explanation

Virtual environments isolate package dependencies for different projects, preventing conflicts. Use the built-in venv module to create environments, and use pip to install packages from PyPI.

Code Examples

Example 1 — Basics

This example introduces the fundamental syntax and concepts.

python
# Create env: python -m venv .venv
# Activate Windows: .venv\Scripts\activate
# Install package: pip install requests

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
# requirements.txt dependencies pin file
# requests==2.31.0
# Run: pip install -r requirements.txt

Example 3 — Advanced Example

This example shows clean, production-grade code structure following senior development standards.

python
# Python verification script checking installed packages safely
try:
    import requests
    print('Requests library is installed and ready.')
except ImportError:
    print('Dependency missing; run pip install requests.')

Visual Flow

The following execution flow represents the step-by-step evaluation inside the interpreter:

text
Create env directory → Update system search paths → Install isolated packages via pip

Common Mistakes

Review these common pitfalls when working with this topic:

  • Installing packages globally instead of inside a virtual environment.
  • Forgetting to activate virtual environments before running pip installs.
  • Not pinning package versions in requirements.txt, which can break builds later.
  • Committing the virtual environment directory (.venv) to version control.

Best Practices

Enforce these Pythonic best practices in your codebase:

❌ Don't
python
pip install requests # Installs globally, risking conflicts
✅ Do
python
python -m venv .venv
.venv\Scripts\activate
pip install requests # Correct isolated environment install

Quick Revision

Use these key summaries for last-minute revision:

  • Virtual environments prevent package version conflicts.
  • venv module creates local environments.
  • pip installs third-party packages.
  • requirements.txt lists project packages.
  • pip freeze prints current environment packages.
  • Never check .venv folders into Git.