Use pre-commit, commit-msg, and pre-push git hooks to fix your Python code ASAP

Learn to use Git hooks to boost your coding efficiency

Lynn Kwong
6 min readSep 19, 2021


In your daily development work, it’s common that you accidentally make some mistakes in your Git commits that violate the regulations in your institution. These mistakes can be as minor as embarrassing to your colleagues, or as major as destructive to your application. It would be great if these mistakes can be detected at an early stage. Luckily, Git hooks can help with this situation.

Photo by Vishal Jadhav on Unsplash.

Git can run custom scripts, which are the so-called hooks, automatically when certain important actions occur. There are two types of hooks in Git, namely client-side and server-side. Client-side hooks are triggered by client operations such as committing or pushing, while server-side hooks run on network operations such as receiving pushed commits. Normally we only work with client-side hooks and they will be the focus of this post.

There are quite a few Git hooks available on the official page. However, most of them are rarely used. In this post, the three most commonly used Git hooks will be introduced. The concepts will be introduced briefly, followed by hands-on code examples, which shall make them fairly easy to understand.

The Git hooks are stored in the hooks subdirectory of the .git directory, which is automatically generated after you run git init or clone a remote repository.

To enable a Git hook, we must put a corresponding script file in the .git/hook directory. The script file must have a predefined name, without any extension, and is executable. For example, the script file can be pre-commit, commit-msg or pre-push.

It should be noted that client-side hooks are not copied when you clone a repository. Therefore, you need to manually copy them to the .git/hooks directory in your local repository.

pre-commit hook

The pre-commit hook is run before a commit is created. It can be used to inspect the code that’s about to be committed. If the pre-commit hook exits with a non-zero status, the commit will be aborted. This behavior can be bypassed git commit --no-verify.



Lynn Kwong

I’m a Software Developer ( keen on sharing thoughts, tutorials, and solutions for the best practice of software development.