Without isolation, projects fight over package versions and your system Python gets broken.
Third-party packages come from PyPI, the Python Package Index, and are installed with pip. Installing into the system interpreter is a bad idea: different projects need different versions, and many Linux distributions and Homebrew now refuse it outright with an "externally managed environment" error (PEP 668).
The answer is a virtual environment: a directory containing its own python and its own site-packages. Create and activate one per project:
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install requestsWhile active, python and pip refer to the venv; deactivate leaves it. Activation is just a convenience that edits your PATH — you can also run .venv/bin/python script.py directly. Don't commit .venv to version control; it's disposable and machine-specific.
Prefer python -m pip to bare pip: it guarantees you're installing into the interpreter you think you are.
Record dependencies so others can reproduce the environment. The simplest form is a requirements.txt file installed with pip install -r requirements.txt; pip freeze prints exact installed versions. Modern projects declare dependencies in pyproject.toml instead (covered in the packaging lesson) and pin exact versions in a lock file.
Many teams now use uv, a fast all-in-one tool that creates venvs, installs packages, manages lock files and can even install Python versions (uv venv, uv add requests, uv run). The concepts are the same: one isolated environment per project.
Example
# Create and use a virtual environment (macOS/Linux shell)
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install "requests>=2.32"
python -m pip list
python -m pip freeze > requirements.txt # record exact versions
deactivate
# Elsewhere: recreate the same environment
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
# Same idea with uv
uv venv && uv pip install requestsRemember
- One virtual environment per project; never install into the system Python
- Use
python -m pipso packages land in the right interpreter - Record dependencies (requirements.txt or pyproject.toml + lock file)
Watch out for
- Committing the
.venvdirectory to git.