Page content

Cleaning up as you go along

Wouldn’t it be nice if everyone cleaned up as they went along? It’s easy to ignore until you are faced with a big clean up.

This is especially true when coding when the pressure is to get something working not matter what so of mess you leave as you progress.

Why not use a tool to keep your messier instincts under control?

Here is where comes in. This easy to configure tool sits between your rushed bad habits and committing locally. When you try to commit a set of tests are run on the files being committed. If the tests fail, you will have to fix your code. Usually pre-commit can clean up for you, but sometimes you will have to clean up your own mess.

To get started follow the excellent guide at but for a quick start to the following:

pip install pre_commit
pre-commit install -f --install-hooks

The configuration is in .pre-commit-config.yaml, an example of which is below:

# See for more information
# See for more hooks
-   repo:
    rev: master
    -   id: python-import-sorter
        args: ['--silent-overwrite']

-   repo:
    rev: v0.720
    -   id: mypy
        args: [--ignore-missing-imports]
-   repo:
    rev: v2.3.0
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-json
    -   id: debug-statements
    -   id: double-quote-string-fixer
    -   id: requirements-txt-fixer
    -   id: flake8
        args: ['--max-line-length=79']

Now when you attempt to commit code the following hooks will run over the changed files.

Handy Commands

Run Against a Single File

pre-commit run --file

Run Against all Files

pre-commit run --all-files *