← Back to libraryQuestion 201 of 468
🐍PythonBeginner

Virtual Environments and pip

📌 Definition:

A virtual environment is an isolated Python environment with its own installed packages, so each project's dependencies don't conflict. pip installs packages; requirements.txt pins them for reproducibility.

📖 Detailed Explanation:

python -m venv .venv creates an environment; you activate it (source .venv/bin/activate) so pip install selenium pytest installs into that isolated environment, not system Python. pip freeze > requirements.txt captures exact versions, and pip install -r requirements.txt reproduces them on another machine or in CI — the Python equivalent of package-lock.json. Isolation prevents 'works on my machine' issues from clashing global packages. Tools like pipenv/poetry add lockfiles and dependency resolution on top.

🔑 Key Points:
  • venv isolates each project's packages
  • pip install adds packages; pip freeze pins versions
  • requirements.txt reproduces the environment in CI
  • Prevents global dependency conflicts
🌍 Real-World Example:

A CI job runs python -m venv .venv && pip install -r requirements.txt so the test suite uses the exact Selenium/pytest versions the author tested with — no surprise version drift.

🎯 Scenario-Based Interview Question:

Two projects need different Selenium versions and keep breaking each other. What's the fix?