What are Python Virtual Environments?
Virtual environments are isolated Python environments that allow you to install packages for specific projects without affecting your system-wide Python installation.
Why Use Virtual Environments?
- Dependency Isolation: Different projects can use different versions of the same package
- Clean Development: Avoid polluting your global Python installation
- Reproducibility: Easily share project dependencies with others
- Version Control: Manage Python versions alongside package versions
Common Virtual Environment Tools
venv (Built-in)
Create a virtual environment
python -m venv myenv
Activate (Linux/macOS)
source myenv/bin/activate
Activate (Windows)
myenv\Scripts\activate
Deactivate
deactivate
virtualenv
Install
pip install virtualenv
Create a virtual environment
virtualenv myenv
Activate (Linux/macOS)
source myenv/bin/activate
Activate (Windows)
myenv\Scripts\activate
conda
Create environment
conda create --name myenv python=3.9
Activate
conda activate myenv
Deactivate
conda deactivate
Poetry
Install
curl -sSL https://install.python-poetry.org | python3 -
Create a new project
poetry new project-name
Add dependencies
poetry add package-name
Activate
poetry shell
Managing Dependencies
pip
Install packages
pip install package-name
Save dependencies
pip freeze > requirements.txt
Install from requirements
pip install -r requirements.txt
Poetry
# Dependencies are managed in pyproject.toml
poetry add package-name
poetry add package-name==1.2.3 # specific version
poetry add "package-name>=1.2.3,<2.0.0" # version constraints
Best Practices
- Always use virtual environments for new projects
- Include activation in your workflow scripts/documentation
- Version control your dependency files (requirements.txt, pyproject.toml)
- Don't commit the virtual environment directory (add to .gitignore)
- Use a consistent naming convention for your environments
Troubleshooting
- Activation not working: Ensure you're using the correct activation command for your OS
- Package not found: Verify the environment is activated and the package is installed
- Multiple Python versions: Specify the Python version when creating the environment
Advanced Usage
Using different Python versions
With virtualenv
virtualenv -p python3.8 myenv
With conda
conda create --name myenv python=3.8
Project-specific configurations
# Set environment variables in .env file
DEBUG=True
API_KEY=your_secret_key
# Use python-dotenv to load them
pip install python-dotenv
Virtual environment wrappers
- pyenv-virtualenv: Combines pyenv with virtualenv
- virtualenvwrapper: Provides commands to manage multiple environments
- pipenv: Combines pip and virtualenv functionality