Tools I use: pre-commit

In my day-to-day, I commit a lot into production, pre-commits helps me get there faster, and cleaner. Today I’ll be going through what it is and how to use it with Python.


pre-commit is a library that allows you to run checks on your code before you commit it to your repository. It’s kind of like the final double-check you do before you hand over your exam.

The Concept:

Typically, code lives in two worlds, your local machine and a remote repository hosted somewhere like GitHub or Gitlab. What pre-commit enables you to do is run to hooks which automatically point things out such as trailing whitespace and incorrect .yaml files this should make your life easier as you discover errors quickly. These hooks run every time you run git commit


pre-commit for Python can be installed via pip by running pip install pre-commit


Running pre-commit sample-config will generate a sample output in your terminal, write this to a file, by running the following: pre-commit sample-config > .pre-commit-config.yaml

The generated file should look like this:


  • repo indicates where the hooks have come from.
  • rev is the release of the given repository.
  • hooks details the individual checks that are run

If we wanted to add something like the flake8 linter to our .pre-commit file, we’d simply head to the repository, and grab the URL and release version. Now, our .yaml file would start looking something like this:

Now, we’re ready to test our code.


Let’s take a crummy Python script, initialize a git repository in our a directory, and run commit it to test pre-commit.

My crummy script violates PEP8 in various ways (it’s too wide, and it has trailing whitespace etc.)

Now if I try to commit this by running git add and git commit -m “Added the file, boss” I receive the following errors via pre-commit:

After I clean up my code by getting rid of unused imports, formatting the code to comply with PEP8, etc, and try to add and commit again, I receive the following:

No errors 👌 I’m now ready to push my code onto the repository and hopefully, this’ll save me time from failing style checks in the CI/CD pipeline and save some embarrassment along the way.

About this blog:

In these posts, I’m aiming to detail my experience with various tools I use on a day to day in the simplest form possible. When looking for educational content I often struggle to learn because:

  1. There is a lot of hype (too many technologies)
  2. People who write the documentation usually don't understand what it is like not to understand it.

I’m aiming to distill my learnings into writing to improve the reader’s knowledge, and my ability to write technical documentation and posts.

Cheers, Paul.