By the end of this lesson, you will be able to create and activate a Python virtual environment to isolate project dependencies from your global system installation.
What it is
A virtual environment is an isolated directory containing its own Python interpreter and pip executable. It allows you to install packages for one project without affecting others or the global system. Think of it as a sandboxed workspace where each project has its own set of tools and libraries.
Related terms: venv (the standard library module), requirements.txt (a file listing dependencies), site-packages (where installed libraries live).
Why it matters
- Dependency Isolation: Project A can use Django 4.0 while Project B uses Django 3.2 without conflict.
- Reproducibility: You can share a
requirements.txtfile so teammates install the exact same versions. - Clean System: Prevents "dependency hell" by keeping global site-packages minimal.
- Safety: Reduces the risk of breaking system tools that rely on specific Python package versions.
Syntax or steps
- Create: Run
python -m venv <directory_name>. This generates a folder with the necessary structure. - Activate: Source the activation script. This modifies your shell's PATH to prioritize the virtual environment's binaries.
- Install: Use
pip installas usual; packages go into the local environment. - Deactivate: Run
deactivateto return to the global Python context.
Example
# Create a virtual environment named .venv in the current directory
python -m venv .venv
# Activate it (Linux/macOS)
source .venv/bin/activate
# Verify isolation: check which python is being used
which python
# Install a package locally
pip install requests
# List installed packages in this environment
pip list
# Deactivate when done
deactivate
Explanation: The first command builds the environment. The second command updates your terminal session so that typing python or pip points to the files inside .venv, not the system-wide ones. The which python command confirms this path change. Finally, deactivate restores your original shell configuration.
Common mistakes
- Forgetting to activate: Installing packages while inactive puts them in the global scope. Always check your prompt for the environment name (e.g.,
(.venv)). - Committing the environment folder: Never add
.venvto Git. Add it to.gitignore. Only commitrequirements.txt. - Mixing Python versions: Ensure you run
python -m venvusing the correct Python version if multiple are installed (e.g.,python3.11 -m venv .venv). - Hardcoding paths: Do not call
.venv/bin/pythondirectly in scripts unless necessary; rely on activation for cleaner code execution.
When to use it
| Scenario | Recommended Tool | Reason |
|---|---|---|
| Standard Web/App Development | venv |
Built-in, lightweight, sufficient for most projects. |
| Data Science / Complex Dependencies | conda |
Handles non-Python binary dependencies (like C libraries) better. |
| Quick Script / One-off Task | Global Install | Overhead of creating an env may outweigh benefits for trivial tasks. |
Practice
Guided Exercise: Create a new folder called test_project. Inside it, create a virtual environment named myenv. Activate it and install the flask package. Check that flask appears in pip list but does not appear when you deactivate and check again.
Challenge: Generate a requirements.txt file from your active environment using pip freeze > requirements.txt. Then, delete the myenv folder, recreate it, and reinstall all dependencies using pip install -r requirements.txt.
Quick check
Q: What happens if you run pip install numpy without activating your virtual environment?
A: NumPy will be installed in your global Python site-packages, potentially causing version conflicts with other projects that require different NumPy versions.
Summary
Virtual environments provide essential isolation for Python projects, ensuring that dependencies do not clash across different applications. By mastering venv creation, activation, and deactivation, you maintain a clean development workflow and reproducible builds.