Virtual Environments
A virtual environment is an isolated Python installation for a project. It keeps dependencies separate so different projects can use different library versions.
Creating a venv
# Create
python -m venv .venv
# Activate
# Windows:
.venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate
# Deactivate
deactivateAfter Activation
# pip now installs into .venv only
pip install flask
pip install "sqlalchemy>=2.0"
# Save dependencies
pip freeze > requirements.txt
# Install on another machine
pip install -r requirements.txtvenv vs conda vs poetry
"""
venv: Built-in, simple, lightweight
conda: Manages Python itself + packages, great for data science
poetry: Modern dependency resolver + lock file + build tool
pipenv: Combines pip + virtualenv with Pipfile
"""pyproject.toml (Modern)
[project]
name = "myapp"
version = "1.0.0"
requires-python = ">=3.10"
dependencies = [
"flask>=3.0",
"sqlalchemy>=2.0",
]Best Practices
# Add to .gitignore:
.venv/
__pycache__/
*.pyc
# Always activate before working:
source .venv/bin/activate