Virtual Environments
Isolate project dependencies with venv.
Here's the problem virtual environments solve.
Imagine two projects on your machine: an old one that needs flask==1.0 and a new one that needs flask==3.0. If you install packages globally, there's only ONE flask — installing 3.0 breaks the old project, downgrading breaks the new one.
A virtual environment (venv) gives each project its own private set of packages. Packages installed inside one environment are invisible to every other project. Conflict gone.
The full lifecycle:
# 1. Create one (a folder named .venv appears in your project)
python -m venv .venv
# 2. Activate it
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows
# Your prompt changes — you're inside:
(.venv) $ pip install requests # installs ONLY for this project
# 3. Leave when done
deactivateWhile active, python and pip point at the environment's own copies. Everything you install lands in .venv/, not in your global Python.
What happens to packages you install while a virtual environment is active?
- AThey're installed globally for all projects
- BThey're installed only inside that virtual environment
- CThey're installed temporarily and deleted on deactivation
- DThey're stored in a cloud registry
Create a virtual environment in a folder called .venv:
python -m ___ .venvProfessional habits around virtual environments:
- One venv per project, created inside the project folder
- Never commit it — add
.venv/to.gitignore. It's hundreds of megabytes of regeneratable files - Recreate freely — deleting
.venv/loses nothing thatpip install -r requirements.txtcan't restore
my-project/
├── .venv/ ← local only, in .gitignore
├── requirements.txt ← committed: the recipe to rebuild .venv
├── main.py
└── .gitignoreForgot whether you're inside one? Look for (.venv) at the start of your prompt, or run pip -V — it prints which environment pip belongs to.
Why should you add the .venv/ directory to .gitignore?
- AIt contains sensitive API keys
- BIt's huge and can always be rebuilt from requirements.txt
- CGit can't handle Python files
- DVirtual environments stop working after a commit