How to Create a Minimal Makefile for Python Projects

Every time I start a new Python project my first step is to create:

  1. GIT repository
  2. virtual environment
  3. requirements.txt file

All project dependencies listed in the requirements.txt file will be installed in the virtual environment.

Next step is to create a simple Makefile with make targets. They simplify managing the project, building artefacts, testing and deploying the package.

I need to be able to:

  • activate virtual environment
  • install dependencies listed in the requirments.txt file
  • install the project (for development or testing)
  • run tests
  • clean files and directories
  • build wheel and tar distributions

To keep it simple let’s assume that Python3 virtual environment is already created and activated.

Below is a small code snippet (a part of the Makefile) that illustrates how to combine virtualenv and make.

venv: venv/bin/activate
venv/bin/activate: requirements.txt
    test -d venv || virtualenv venv
    venv/bin/pip install -Ur requirements.txt
    touch venv/bin/activate

devbuild: venv
    venv/bin/python setup.py install

devinstall: venv
    venv/bin/pip install --editable .

test: venv
    venv/bin/pytest tests/test_vm.py -v

How does it work? The venv target builds virtual environment and installs Python packages listed in the requirements.txt file. If all packages are installed and up to date nothing happens. The venv make target can be used as a dependency for other targets or called directly to build venv from scratch:

$ make venv

Leave a Reply