Interview Prep/Build Tools (Java, Node.js, Python, .NET)/Python builds (pip, venv, requirements.txt)

What is a Python virtual environment and why do we need it?

BeginnerConceptPython builds (pip, venv, requirements.txt)
Answer

Short answer

A virtual environment (venv) is a private folder with its own Python interpreter link and its own installed packages, for one project. It stops projects on the same machine from fighting over package versions, and keeps the system Python clean.

Explained in simple words

Without venvs, every project shares one big bag of packages. Project A needs django 4.2, project B needs django 5.0 — impossible. A venv gives each project its own bag.

Commands

python3 -m venv .venv
source .venv/bin/activate          # prompt shows (.venv)
pip install -r requirements.txt    # goes into .venv/lib/python3.12/site-packages
which python                       # .../project/.venv/bin/python
deactivate

Rules

  • .venv/ goes in .gitignore — it's recreated from requirements.txt.
  • On modern Debian/Ubuntu, pip install system-wide fails with "externally-managed-environment" — use a venv (or pipx for CLI tools).
  • In Docker, the container is already isolated, so a venv is optional (useful in multi-stage builds to copy one folder).

What to say in the interview

"A venv isolates a project's dependencies from other projects and the OS Python. We create it per project, install from a pinned requirements file, and never commit it."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Python apps: pip, venv & requirements.txt

More on Python builds (pip, venv, requirements.txt)