[tutorial_ml:04] Leveraging pre-commit for Code Quality Assurance

Rafa Felix
3 min readDec 8, 2023

--

Photo by Andrea Piacquadio from Pexels: https://www.pexels.com/photo/crop-businessman-giving-contract-to-woman-to-sign-3760067/

Introduction

pre-commit is a powerful tool used to manage and maintain pre-commit hooks. These hooks are automated checks that run before each commit, ensuring that your code adheres to defined standards and helping to prevent common issues. Integrating pre-commit into your workflow can significantly enhance the code quality and consistency of your project.

Prior to installing pre-commit, make sure that your repository is a github repo.

Install Pre-Commit: Start by installing pre-commit using pip:

pip install pre-commit

Configure Pre-Commit Hooks: Create a .pre-commit-config.yaml file at the root of your repository. In this file, specify the hooks you want to use. For example:

repos:
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.9.0
hooks:
- id: rst-backticks
  - repo: https://github.com/pycqa/flake8.git
rev: 3.9.2
hooks:
- id: flake8
exclude: 'test|env|docs'
additional_dependencies:
- "flake8-annotations==2.9.0"
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.950
hooks:
- id: mypy
additional_dependencies:
- "types-pytz"
- repo: https://github.com/kynan/nbstripout
rev: 0.5.0
hooks:
- id: nbstripout
files: ".ipynb"
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
- id: trailing-whitespace
exclude: ./tests/
- id: end-of-file-fixer
exclude: ./tests/
- id: check-yaml

Install Hooks: Run pre-commit install to set up the git hook scripts. This command installs the pre-commit script into your .git/hooks/pre-commit.

pre-commit install

How Pre-Commit Enhances Your Workflow

  • Automated Code Quality Checks: Before each commit, pre-commit runs the configured hooks, automatically checking your code for formatting errors, trailing whitespaces, syntax errors in YAML files, and more.
  • Consistency Across the Team: By including the .pre-commit-config.yaml file in your repository, you ensure that every contributor adheres to the same coding standards, enhancing consistency and reducing code review time.
  • Customisation and Extensible: pre-commit supports a wide range of hooks for various languages and frameworks. You can customize it to suit the specific needs of your project, including setting up hooks for Python formatting (like flake8, black, isort) and more.

Integrating pre-commit into your Python project setup brings a structured approach to code quality. It automates the enforcement of coding standards, leading to cleaner, more maintainable, and error-free code.

--

--

Rafa Felix
Rafa Felix

Written by Rafa Felix

Machine Learning | Computer Vision | NLP | Vision and Language

No responses yet