Python virtual environments with venv: the practical guide
Installing every project's packages into one global Python is how version conflicts begin. The standard library's answer is venv: lightweight virtual environments, each with its own independent set of installed packages. This is the practical guide, from the official Python documentation.
What a virtual environment is
Per the Python docs: a virtual environment is created on top of an existing Python installation (its "base" Python) and is by default isolated from the base environment's packages, so only what you explicitly install inside it is available. Conventionally it lives in a directory named .venv or venv in your project.
Create one
python -m venv .venv
The docs explain what this creates: the target directory with a pyvenv.cfg file pointing at the base Python, a bin subdirectory (or Scripts on Windows) with the Python executable, and a lib/pythonX.Y/site-packages directory for the environment's own packages.
Activate it
# Linux / macOS source .venv/bin/activate # Windows (Command Prompt) .venv\Scripts\activate.bat
After activation, python and pip resolve to the environment's copies, so pip install touches only this project.
Why bother
- Two projects can pin conflicting versions of the same package without a fight.
pip freezeinside an environment lists exactly what that project needs, which makes deployment and collaboration reproducible.- Deleting the directory removes the whole environment cleanly; nothing leaks into the system Python.
Common mistakes
- Committing
.venvto Git. It is machine-specific and huge; commit a requirements file instead and keep.venvin your.gitignore(see our .gitignore guide). - Running scripts with the system Python after activating; check with
which python. - Moving or renaming the project folder; paths inside the environment point at its original location, so recreate it after a move.
Next steps: build your first Flask web app and read and write JSON files in Python.
