pip and virtual environments
Third party packages are how Python punches above its weight. pip installs them, and virtual environments keep each project's packages separate so that upgrading one project never breaks another.
Installing a package
pip install requestsThis downloads requests from the Python Package Index (PyPI) and installs it. On some systems you need pip3 or python -m pip. The last form always uses the pip that belongs to the Python you are running, which avoids a lot of confusion.
python -m pip install requestsThen use it like any module:
import requests
r = requests.get("https://api.github.com")
print(r.status_code)Other pip commands
pip install requests==2.32.0 # a specific version
pip install "requests>=2.31" # a minimum version
pip install --upgrade requests
pip uninstall requests
pip list # everything installed
pip show requests # details of one packageWhy virtual environments
Installing everything globally causes two problems: different projects need different versions of the same package, and it becomes impossible to know what a project actually depends on. A virtual environment is a private folder with its own Python and its own packages.
Creating one
From your project folder:
python -m venv .venvThis creates a .venv folder. Activate it:
# macOS and Linux
source .venv/bin/activate
# Windows (Command Prompt)
.venv\Scripts\activate.bat
# Windows (PowerShell)
.venv\Scripts\Activate.ps1Your prompt now shows (.venv). Everything you pip install goes into this folder only. deactivate returns to the global Python.
Add .venv/ to your .gitignore; it should never be committed.
Recording dependencies
Write the packages your project needs to a requirements.txt file so anyone can recreate the environment:
pip freeze > requirements.txtnumpy==2.1.0
pandas==2.2.2
scikit-learn==1.5.1And on another machine:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtModern alternatives
- uv is a very fast drop in replacement for pip and venv:
uv venv,uv pip install. - Poetry and PDM manage dependencies through
pyproject.tomland handle publishing. - conda is common in data science and can also install non Python libraries.
All of them solve the same problem. Start with venv and pip because every tutorial and error message assumes them.
Editors and virtual environments
VS Code and PyCharm detect .venv automatically. If imports are flagged as unresolved, select the interpreter inside .venv in the editor's Python settings.
Practice
- Create a virtual environment in a new folder, activate it and install
rich. Runpython -m richto see it work. - Freeze the requirements to a file and read the file.
- Deactivate, then try
python -c "import rich"globally to confirm the package is isolated.
