Adding Git Pre-commit hooks for Python projects
Are you the person who spends more time identifying the indentations and code standards instead of reviewing the logic in the Pull Request. Then below steps will definitely help you in automating some reviewing for you.
Git Pre-commit hook scripts are useful for identifying simple issues before committing the code to remote. We run our hooks on every commit to automatically point out issues in code such as missing semicolons, trailing whitespace, and debug statements.
Below we are going to see step by step procedure to enable pre-commit hooks for Python projects with Black (code formatter) and Flake8 (style guide)
We are going to use a pre-commit framework for enabling pre-commit hooks. you can also follow the steps in the pre-commit website (which is missing configurations for black and fake8).
Get Surya’s stories in your inbox
Join Medium for free to get updates from this writer.
Step 1: Install pre-commit
pip install pre-commitStep 2: Add configurations for pre-commit
- create a file named .pre-commit-config.yamlin the /root directory
- Add the below code inside the .pre-commit-config.yaml file
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.4.0
hooks:
- id: flake8
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: blackStep 3: Add pre-commit hook by running the below code
pre-commit installStep 4: Add the configuration for Black and Flake8 — you can always modify the configuration based on your needs.
Create .black configuration file in the root directory and add the below configuration
[tool.black]line-length = 79
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
Create .flake8 configuration file in the root directory and add the below configuration
[flake8]
ignore = E203, E266, E501, W503, F403, E401, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9Step 5: No step 5, that’s it your pre-commit hook setup for your Python project is done. Try committing the changes, you should see the following steps executed.








