Why Virtual Environments?
Virtual environments create isolated Python environments for each project. Without them, different projects requiring different package versions would conflict.
Creating a Virtual Environment
# Standard library venv
python3 -m venv myproject-env
# Activate it
source myproject-env/bin/activate # macOS/Linux
myproject-env\Scripts\activate # Windows
# Install packages — they stay isolated
pip install requests flask
# Deactivate when done
deactivate
Managing Dependencies
# Save current dependencies
pip freeze > requirements.txt
# Install from requirements.txt
pip install -r requirements.txt
Using Poetry (Recommended)
# Create new project
poetry new my-project
cd my-project
# Add dependencies
poetry add requests
poetry add --group dev pytest black
# Install all dependencies
poetry install
Best Practices
- Always use virtual environments — never install globally
- Add
venv/to.gitignore - Pin versions for reproducibility
- Use Poetry for new projects