Pre-commit hooks

Pre-commit hooks

Mar 24, 2023·

2 min read

Play this article

A pre-commit hook is a script that is executed before a commit is made in version control systems such as Git. Pre-commit hooks can be used to perform tasks such as running tests, linting code, or checking for formatting errors. The pre-commit hook provides an extra layer of automation to make sure only valid code is committed to the repository.

Pre-commit hooks can be used for the following tasks:

  • Running tests

  • Linting code

  • Checking formatting errors

  • Enforcing coding standards

  • Checkpointing data before making changes to the repository

  • Undoing undesirable commits.

Installation Instructions

The pre-commit package is available on PyPI and can be installed using the pip install pre-commit command.

After installing the package, you can create a .pre-commit-config.yaml file in the project's root directory, which contains the configuration for the pre-commit hooks. You can then add the desired pre-commit hooks to this file and include the command(s) that should be executed in each hook. Finally, you can run the pre-commit install command from the root directory to install the pre-commit hooks and enable them for the project.


    - repo:
      rev: v4.4.0
      - id: detect-aws-credentials
        args: ["--allow-missing-credentials"]
      - id: detect-private-key
      - id: check-added-large-files
      - id: check-symlinks
      - id: check-merge-conflict
      - id: check-yaml
      - id: debug-statements
    - repo:
      rev: 23.1.0
      - id: black
        args: ["--line-length", "80"]
    - repo:
      rev: "1.7.5"
      - id: bandit
        args: ["--skip", "B101", "B703", "B308"]
    - repo:
      rev: 6.0.0
      - id: flake8
        args: ["--config", "setup.cfg"]
    - repo:
      rev: 5.12.0
      - id: isort
        args: [ "--profile", "black", "--line-length", "80",]

This pre-commit hook configuration will run several checks on your code before it is committed. The detect-aws-credentials hook will ensure that AWS credentials are not accidentally added to your project files.

The detect-private-key hook will detect any private key files in your changes. The check-added-large-files hook will check for large files added to your repo.

The check-symlinks hook will make sure no broken symlinks are added.

The check-merge-conflict hook will detect merge conflicts in your changes.

The check-yaml hook will check YAML files for errors.

The debug-statements hook will detect debug statements in your code.

The black hook will check your code for formatting using the Black code style.

The bandit hook will check your code for any potential security issues.

The flake8 hook will check for code style compliance. It will also look for configuration files in setup.cfg.

And finally, the isort hook will check your imports for proper sorting.