Sub topic 1
Python Virtual Environments and pip: Isolating and Managing Project Dependencies
Prerequisites
You should know how to run commands in a terminal, run a Python script, import a module, and use Python 3 from the command line.
Why projects need their own environments
A Python project depends on packages, which are reusable libraries installed separately from Python. Different projects may require different versions of the same package. Installing every package globally can create conflicts: upgrading a package for one project may break another.
A virtual environment is a project-specific directory containing an isolated Python interpreter and package directory. It lets each project select its own dependencies without changing the system installation or other projects.
Creating a virtual environment with python -m venv
From the project directory, run:
python3 -m venv .venvThe venv module is part of Python's standard library. This command creates .venv, a conventional name for the environment directory. On Windows, the Python launcher is commonly used:
py -m venv .venvThe command uses the Python interpreter that runs it. If several Python versions are installed, verify which one you selected before creating the environment.
Inside a virtual environment: pyvenv.cfg, the interpreter, and site-packages
The pyvenv.cfg file records the base Python installation. The environment also contains its own interpreter entry point and a site-packages directory. site-packages holds packages installed for that environment.
The environment is isolated at the package level, but it normally reuses the base interpreter's standard library. Deleting .venv removes the environment, not your project source code.
Activating and deactivating on Linux, macOS, and Windows
Activation changes shell commands so python and pip resolve to the environment.
source .venv/bin/activate
python -c "import sys; print(sys.prefix); print(sys.base_prefix)"
deactivateIn Windows PowerShell:
.venv\Scripts\Activate.ps1
deactivateThe output shows different sys.prefix and sys.base_prefix values while the environment is active.
| Platform | Activation command |
|---|---|
| Linux or macOS | `source .venv/bin/activate` |
| Windows PowerShell | `.venv\Scripts\Activate.ps1` |
Exercise
Why should two projects use separate virtual environments?
Show answer
They may require incompatible package versions, and separate environments prevent one project's installation from changing the other.