Virtual Environments
Overview
If you install every third-party package (like Django, Pandas, or Requests) globally onto your system, you will inevitably encounter 'Dependency Hell'. Project A might require Django 3.0, while Project B requires Django 4.0. Virtual Environments solve this by creating isolated, self-contained Python installations for each project. They ensure that dependencies, binaries, and versions are completely sandboxed.
Syntax
# 1. Create a virtual environment named 'venv'
python -m venv venv
# 2. Activate the environment (Mac/Linux)
source venv/bin/activate
# 2. Activate the environment (Windows)
venv\Scripts\activate
# 3. Install packages safely into the sandbox
pip install requests flask
# 4. Freeze dependencies into a file for other developers
pip freeze > requirements.txt
# 5. Deactivate to return to global system Python
deactivateCommon Pitfalls
- Forgetting to ACTIVATE the environment before running
pip install, permanently polluting the global OS Python installation. - Committing the
venvfolder to GitHub. It contains tens of thousands of binary executables and OS-specific files. ALWAYS addvenv/to your.gitignorefile. You only share therequirements.txt.
Interview Questions
requirements.txt file critical for project collaboration?It locks down the exact package versions your project depends on. Another developer can simply run pip install -r requirements.txt to perfectly replicate your environment, eliminating 'works on my machine' bugs.
Real-World Example
Modern production alternatives to the standard venv.
# While 'venv' is built into Python, modern professional projects
# increasingly rely on advanced tooling for dependency resolution:
# - poetry: Standardizes packaging and robust dependency management.
# - pipenv: Combines pip and venv into a single seamless workflow.
# - uv / ruff: Blazing fast Rust-based package managers and linters.Check Your Knowledge
Test your understanding of Virtual Environments with these quick questions.