Kodokon kodokon.com

Virtual environments, pip and a clean project

Isolate each project in its own venv, pin the dependencies and adopt a reproducible project structure.

8 min · 3 questions

Open this lesson in Kodokon

Installing the dependencies of all your projects in the same interpreter leads straight to a version conflict: project A needs requests 2.31, project B an incompatible version. The virtual environment (venv) isolates each project: its interpreter, its pip, its packages. It is the non-negotiable professional practice - one project, one environment, recreatable identically on any machine.

BASH
python -m venv .venv
source .venv/bin/activate
# On Windows:
# .venv\Scripts\activate
python -m pip install requests
python -m pip list
Create, activate and populate a virtual environment

To make the installation reproducible, pin the versions. pip freeze exports the entire environment, transitive dependencies included, with exact versions: maximum reproducibility, laborious updates. The modern approach separates the two needs: the direct dependencies declared in pyproject.toml with loose constraints, and a lock file generated for the exact installation. At the scale of a small project, requirements.txt remains perfectly respectable.

BASH
python -m pip freeze > requirements.txt
# On another machine:
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
Freeze then rebuild the environment identically

On the structure side, the src layout is the reference: the code lives in src/<package>/, the tests in tests/, the configuration in pyproject.toml. The point of the src folder is not cosmetic: it prevents accidentally importing the local package from the current directory, which would hide packaging errors - your tests run against the actually installed package. During development, pip install -e . installs the project in editable mode.

BASH
mkdir -p src/billing tests
touch src/billing/__init__.py
touch src/billing/invoices.py
touch tests/test_invoices.py
touch pyproject.toml README.md .gitignore
echo ".venv/" >> .gitignore
Skeleton of a project in src layout

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does a virtual environment guarantee?
    • Faster execution of Python code
    • Isolated dependencies for each project
    • Compatibility between Python versions
    • Encryption of the installed packages
  2. What does a requirements.txt generated by pip freeze contain?
    • Only your direct dependencies
    • Every installed dependency, exact versions included
    • The list of packages available on PyPI
  3. Why prefer python -m pip install over pip install?
    • It is the only syntax accepted inside a venv
    • The command targets the pip of the active interpreter
    • The installation is faster