Question presented to candidate: "Why do Python developers create a virtual environment for each project? What problem does it solve, what is actually inside one, and how does Python know it is running in one?"
What a strong answer should cover:
- Without isolation, every project shares one
site-packages, so only one version of each library can be installed; two projects needing different versions conflict, and installing into the system Python can break OS tools - A virtual environment is a folder with its own
site-packages, apythonlink (or copy) to a base interpreter, and apyvenv.cfg; it shares the base interpreter and standard library, it is not a copy of Python - Python detects it at start-up from
pyvenv.cfgnext to or one level above the executable, and setssys.prefixto the venv whilesys.base_prefixstays at the base install;sys.prefix != sys.base_prefixmeans "in a venv" - Activation only changes
PATH(andVIRTUAL_ENV, the prompt); running the venv'spythondirectly works without activating - Reproducibility comes from pinning what goes into the venv (
requirements.txt, a lockfile such asuv.lock); the venv itself is disposable and should not be committed - PEP 668 "externally managed" system Pythons (Debian 12, Ubuntu 23.04+) now refuse
pip installoutside a venv;python -m venv(PEP 405, Python 3.3) oruv venvare the standard tools
Code / implementation expected: Optional β the python -m venv .venv / activate / install workflow, or checking sys.prefix against sys.base_prefix.