Python Virtual Environments¶
Learning Objectives
- Understand why virtual environments are crucial for reproducible research
- Learn how to create and manage Python virtual environments
- Master dependency management with requirements.txt
- Develop best practices for environment management in scientific projects
Why Virtual Environments?¶
Virtual environments solve several critical problems:
- Isolation: Keep project dependencies separate
- Reproducibility: Ensure consistent package versions across different machines
- Conflict Prevention: Avoid package version conflicts between projects
- Clean Management: Easy to create, delete, and recreate environments
Virtual Environment Tools¶
venv (Built-in)¶
Python's built-in solution, simple and lightweight:
# Create virtual environment
python -m venv myenv
# Activate virtual environment
# On Unix/macOS:
source myenv/bin/activate
# On Windows:
myenv\Scripts\activate
# Deactivate
deactivate
There are other tools for python virtual environment management, such as conda
, pyenv
, pipenv
, poetry
, uv
, etc. You can choose one of them to manage your dependencies. Here we will focus on venv
and requirements.txt
.
Managing Dependencies¶
pip Requirements¶
-
Generate requirements.txt:
-
Install from requirements.txt:
Recommended Workflow¶
-
Project Setup:
-
Development Workflow:
-
Collaboration Workflow:
-
Deployment Workflow: