Topic 18 of 64
Virtual Environments & pip
Overview
Virtual environments isolate Python dependencies per project, preventing version conflicts between projects. They are mandatory for professional Python development and understanding them is expected in any Python job interview.
Syntax
python
# Create virtual environment
python -m venv venv
# Activate (macOS/Linux)
source venv/bin/activate
# Activate (Windows)
venv\Scripts\activate
# Install packages
pip install flask django fastapi
pip install -r requirements.txt
# Save current dependencies
pip freeze > requirements.txt
# Uninstall
pip uninstall flask
# pip list installed packages
pip list
pip show flask # details about a package
# Modern: use pyproject.toml + pip
# pyproject.toml
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.backends.legacy:build"
[project]
name = "myapp"
version = "0.1.0"
dependencies = [
"fastapi>=0.100",
"sqlalchemy>=2.0",
"pydantic>=2.0",
]Common Pitfalls
- Never commit the venv/ directory to git — it's large, platform-specific, and can be recreated from requirements.txt.
- Always include exact versions in requirements.txt for reproducible builds — pin with pip freeze, not manual editing.
- Interview tip: Modern Python projects use poetry or pyproject.toml instead of requirements.txt — they handle dev vs production dependencies separately.
Real-World Example
Setting up a professional FastAPI project with virtual environment:
example
python
# Terminal setup
python -m venv .venv
source .venv/bin/activate
# requirements.txt
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
pydantic==2.5.0
python-dotenv==1.0.0
pytest==7.4.3
httpx==0.25.2 # for testing FastAPI
pip install -r requirements.txt
# .gitignore — never commit the venv!
.venv/
__pycache__/
*.pyc
.env
*.db
# .env file (not committed!)
DATABASE_URL=postgresql://user:pass@localhost/mydb
SECRET_KEY=your-secret-key-here
DEBUG=False
# app/config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
secret_key: str
debug: bool = False
class Config:
env_file = ".env"
settings = Settings()