indusai.co

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

terminal
pip install requests

This 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.

terminal
python -m pip install requests

Then use it like any module:

python
import requests
r = requests.get("https://api.github.com")
print(r.status_code)

Other pip commands

terminal
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 package

Why 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:

terminal
python -m venv .venv

This creates a .venv folder. Activate it:

terminal
# macOS and Linux
source .venv/bin/activate

# Windows (Command Prompt)
.venv\Scripts\activate.bat

# Windows (PowerShell)
.venv\Scripts\Activate.ps1

Your 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:

terminal
pip freeze > requirements.txt
output
numpy==2.1.0
pandas==2.2.2
scikit-learn==1.5.1

And on another machine:

terminal
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Modern 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.toml and 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

  1. Create a virtual environment in a new folder, activate it and install rich. Run python -m rich to see it work.
  2. Freeze the requirements to a file and read the file.
  3. Deactivate, then try python -c "import rich" globally to confirm the package is isolated.