Modules and imports · 7 / 16 Theory

Virtual environments, pip and requirements.txt

Real programs use third-party packages, and each project may need different versions of the same package. Installing everything in the system Python ends in conflicts. The solution is one virtual environment per project.

# Terminal (not Python code)
python -m venv .venv                 # creates the environment in the .venv folder
source .venv/bin/activate            # Linux and macOS
.venv\Scripts\activate               # Windows
pip install requests                 # installs a package only in this environment
pip freeze > requirements.txt        # saves the installed versions
pip install -r requirements.txt      # recreates the environment on another computer
deactivate                           # leaves the environment
import sys

print(sys.prefix != sys.base_prefix)    # True inside a virtual environment; False outside
print(sys.version_info >= (3, 8))       # True

# A virtual environment is just a folder with its own copy of "python" and "site-packages".
# "pip list" shows what is installed in the active environment.
  • venv comes with Python. The environment lives in a folder (usually called .venv) that is not committed to the repository.
  • pip is the package installer. pip install name==1.2.3 pins a version; pip install --upgrade name updates it.
  • requirements.txt lists the project's packages and versions. Whoever clones the project creates their own environment and runs pip install -r requirements.txt.
  • For projects that are published, pyproject.toml describes the package and its dependencies (it is the TOML format you saw in the data formats lesson).
  • Before installing anything, check that the right environment is active: its name appears in parentheses in the terminal.