SlideShare a Scribd company logo
Thomas Aglassinger
https://roskakori.at
Helpful pre-commit
hooks for Python and
Django
What is pre-commit?
●
A framework to manage git pre-commit hooks.
●
To perform quality check on code before accepting a
commit.
●
Many handy hooks available through it.
●
Helps you catch many (often minor issues) before they make
it into the repository.
How to get pre-commit
●
Visit https://pre-commit.com/
●
Various methods to install:
– Plain Python: pip install pre-commit
– Anaconda: conda install -c conda-forge pre-commit
– Ubuntu: sudo apt-get install pre-commit
– MacOS: brew install pre-commit
Configuration
●
Add a file “.pre-commit-config”
●
Add the github repositories and hooks you want to run before each commit.
●
Example:
●
Run “pre-commit install”
●
Hooks are checked on
“git commit ...” and commit in IDE
●
Manually run hooks using
“pre-commit run --all-files”
exclude: "^.idea"
repos:
- repo: git://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: mixed-line-ending
args: ["--fix=auto"]
Configuration
●
Add a file “.pre-commit-config”
●
Add the github repositories and hooks you want to run
before each commit.
●
Example: exclude: "^.idea"
repos:
- repo: git://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: mixed-line-ending
args: ["--fix=auto"]
Regex for files and
folders not to check
Source code repository
and version of hooks
to use
Hooks to use
Parameters for a
specific hook
Standard hooks – Text files
●
- repo: git://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
●
trailing-whitespace: remove white space at end of line in
text files
●
mixed-line-ending: detect or fix mixed line endings (e.g
developers on Windows and Unix working on same code)
●
end-of-file-fixer: Ensures that text files end with a newline
character.
Example hooks
Standard hooks – Unwanted files
●
check-byte-order-marker: rejects text files starting with
UTF-8 BOM (as created by various Microsoft tools like
Notepad, causing many Unix tools to fail)
●
check-added-large-files: rejects large files; possibly specify
what is large: args: ["--maxkb=768"]
●
Check-merge-conflict: refuse to commit before all merge
conflicts are resolved
Standard hooks - Python
●
check-ast: check Python syntax
●
requirements-txt-fixer: sorts entries in requirements.txt
●
debug-statements: refuse to commit calls to breakpoints()
and imports of debugger
Standard hooks – Syntax checks
●
check-json
●
check-toml
●
check-xml
●
check-yaml
Pretty print Python
●
Using black (opinionated): https://github.com/psf/black
●
Configure using pyproject.toml
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
[tool.black]
line-length = 120
include = '.pyi?$'
exclude = '''
/(
.eggs
| .git
| venv
| build
| dist
)/
'''
Sort imports consistently
●
Using isort:
https://github.com/timothycrosley/isort
●
Configure using setup.cfg
●
Can be tricky to work with black
→ see example to the right
- repo: https://github.com/timothycrosley/isort
rev: 5.4.2
hooks:
- id: isort
[tool:isort]
# Use project line length.
line_length = 120
# Packages from own projetc
default_section = THIRDPARTY
known_first_party = mytool, niftysite
# Use same style as black.
force_grid_wrap=0
include_trailing_comma = True
multi_line_output=3
use_parentheses=True
# Skip virtual environments.
skip_glob = venv
Flake8 – Semantic Python check
●
Find unused imports, shadowed variables, string formatting,
unreachable code, …
●
Configure using setup.cfg
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.3
hooks:
- id: flake8
[flake8]
max-line-length = 120
ignore = E203, W503
exclude =
.git
build
dist
venv
docs/conf.py
Prettier – Pretty print various formats
for web development
●
Supports JavaScript, CSS, Markdown, HTML, GraphQL, YAML
and others by means of plugins
●
Does not work with Django HTML templates → exclude using
“.prettierignore” (uses same format as .gitignore)
- repo: https://github.com/prettier/prettier
rev: 2.0.5
hooks:
- id: prettier
**/coverage.xml
**/templates/**/*.html
Summary
●
Pre-commit is easy to install and configure.
●
Solves minor minor issues arising when multiple developers
work on the same code.
●
Plenty of available hooks.

More Related Content

What's hot (20)

PDF
Django deployment and rpm+yum
Walter Liu
 
PPTX
Improving WordPress Theme Development Workflow - Naveen Kharwar.
Naveen Kharwar
 
PDF
Introduction to ansible
Mukul Malhotra
 
PDF
Web Applications with Eclipse RT and Docker in the Cloud
Markus Knauer
 
PPTX
Gestión de la configuración - Jenkins ci
Carles San Agustin
 
PPTX
Modern Development Tools
Ye Maw
 
PDF
Introduction to NPM and building CLI Tools with Node.js
Suroor Wijdan
 
PDF
Laravel Poznań Meetup #12 - "Speed up web API with Laravel and Swoole using ...
HighSolutions Sp. z o.o.
 
PPTX
Docker and fig for dev
pranas_algoteq
 
PDF
Nightwatch.js (vodQA Shots - Pune 2017)
Smriti Tuteja
 
PDF
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
PDF
Docker
Kamil Grabowski
 
PDF
[MeetUp][2nd] 컭on턺
InfraEngineer
 
ODP
Elastic search
Rahul Agarwal
 
PPTX
Plone deployment made easy
Kim Chee Leong
 
PDF
Docker command
Eric Ahn
 
PDF
Nginx维护手册
Lei Yang
 
PPT
Newgenlib Installation on Ubuntu 12.04
Rajendra Singh
 
PDF
Vagrant are you still develop in a non-virtual environment-
Anatoly Bubenkov
 
PDF
How to create your own hack environment
Sumedt Jitpukdebodin
 
Django deployment and rpm+yum
Walter Liu
 
Improving WordPress Theme Development Workflow - Naveen Kharwar.
Naveen Kharwar
 
Introduction to ansible
Mukul Malhotra
 
Web Applications with Eclipse RT and Docker in the Cloud
Markus Knauer
 
Gestión de la configuración - Jenkins ci
Carles San Agustin
 
Modern Development Tools
Ye Maw
 
Introduction to NPM and building CLI Tools with Node.js
Suroor Wijdan
 
Laravel Poznań Meetup #12 - "Speed up web API with Laravel and Swoole using ...
HighSolutions Sp. z o.o.
 
Docker and fig for dev
pranas_algoteq
 
Nightwatch.js (vodQA Shots - Pune 2017)
Smriti Tuteja
 
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
[MeetUp][2nd] 컭on턺
InfraEngineer
 
Elastic search
Rahul Agarwal
 
Plone deployment made easy
Kim Chee Leong
 
Docker command
Eric Ahn
 
Nginx维护手册
Lei Yang
 
Newgenlib Installation on Ubuntu 12.04
Rajendra Singh
 
Vagrant are you still develop in a non-virtual environment-
Anatoly Bubenkov
 
How to create your own hack environment
Sumedt Jitpukdebodin
 

Similar to Helpful pre commit hooks for Python and Django (20)

PDF
Software Quality Assurance Tooling 2023
Henry Schreiner
 
PDF
Digital RSE: automated code quality checks - RSE group meeting
Henry Schreiner
 
PDF
Software Quality Assurance Tooling - Wintersession 2024
Henry Schreiner
 
PDF
Princeton Wintersession: Software Quality Assurance Tooling
Henry Schreiner
 
PDF
Tools to help you write better code - Princeton Wintersession
Henry Schreiner
 
PDF
Everything you didn't know you needed
Henry Schreiner
 
PDF
Open source projects with python
roskakori
 
PPTX
Complete python toolbox for modern developers
Jan Giacomelli
 
PDF
Princeton RSE: Building Python Packages (+binary)
Henry Schreiner
 
PDF
Contributing to an os project
Lasse Schuirmann
 
PPTX
The New York Times: Sustainable Systems, Powered by Python
All Things Open
 
PDF
Automate cleaning code in few easy steps!
Ester Beltrami
 
PDF
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
Henry Schreiner
 
DOCX
Testing Gas Mileage Claims Assume that you are working for the C.docx
mattinsonjanel
 
PDF
Jedi Mind Tricks in Git
Johan Abildskov
 
PDF
Python Requirements File How to Create Python requirements.txt
Inexture Solutions
 
PPTX
Jedi Mind Tricks for Git
Jan Krag
 
PDF
Princeton RSE Peer network first meeting
Henry Schreiner
 
DOCX
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
ChantellPantoja184
 
PDF
Python testing like a pro by Keith Yang
PYCON MY PLT
 
Software Quality Assurance Tooling 2023
Henry Schreiner
 
Digital RSE: automated code quality checks - RSE group meeting
Henry Schreiner
 
Software Quality Assurance Tooling - Wintersession 2024
Henry Schreiner
 
Princeton Wintersession: Software Quality Assurance Tooling
Henry Schreiner
 
Tools to help you write better code - Princeton Wintersession
Henry Schreiner
 
Everything you didn't know you needed
Henry Schreiner
 
Open source projects with python
roskakori
 
Complete python toolbox for modern developers
Jan Giacomelli
 
Princeton RSE: Building Python Packages (+binary)
Henry Schreiner
 
Contributing to an os project
Lasse Schuirmann
 
The New York Times: Sustainable Systems, Powered by Python
All Things Open
 
Automate cleaning code in few easy steps!
Ester Beltrami
 
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
Henry Schreiner
 
Testing Gas Mileage Claims Assume that you are working for the C.docx
mattinsonjanel
 
Jedi Mind Tricks in Git
Johan Abildskov
 
Python Requirements File How to Create Python requirements.txt
Inexture Solutions
 
Jedi Mind Tricks for Git
Jan Krag
 
Princeton RSE Peer network first meeting
Henry Schreiner
 
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
ChantellPantoja184
 
Python testing like a pro by Keith Yang
PYCON MY PLT
 
Ad

More from roskakori (16)

PDF
Expanding skill sets - Broaden your perspective on design
roskakori
 
PPTX
Django trifft Flutter
roskakori
 
PDF
Startmeeting Interessengruppe NLP NLU Graz
roskakori
 
PDF
Helpful logging with python
roskakori
 
PDF
Helpful logging with Java
roskakori
 
PDF
Einführung in Kommunikation und Konfliktmanagement für Software-Entwickler
roskakori
 
PDF
Analyzing natural language feedback using python
roskakori
 
PDF
Microsoft SQL Server with Linux and Docker
roskakori
 
PDF
Migration to Python 3 in Finance
roskakori
 
PDF
Introduction to pygments
roskakori
 
PDF
Lösungsorientierte Fehlerbehandlung
roskakori
 
PDF
XML namespaces and XPath with Python
roskakori
 
PDF
Erste-Hilfekasten für Unicode mit Python
roskakori
 
PDF
Introduction to trader bots with Python
roskakori
 
PDF
Python builds mit ant
roskakori
 
PPT
Kanban zur Abwicklung von Reporting-Anforderungen
roskakori
 
Expanding skill sets - Broaden your perspective on design
roskakori
 
Django trifft Flutter
roskakori
 
Startmeeting Interessengruppe NLP NLU Graz
roskakori
 
Helpful logging with python
roskakori
 
Helpful logging with Java
roskakori
 
Einführung in Kommunikation und Konfliktmanagement für Software-Entwickler
roskakori
 
Analyzing natural language feedback using python
roskakori
 
Microsoft SQL Server with Linux and Docker
roskakori
 
Migration to Python 3 in Finance
roskakori
 
Introduction to pygments
roskakori
 
Lösungsorientierte Fehlerbehandlung
roskakori
 
XML namespaces and XPath with Python
roskakori
 
Erste-Hilfekasten für Unicode mit Python
roskakori
 
Introduction to trader bots with Python
roskakori
 
Python builds mit ant
roskakori
 
Kanban zur Abwicklung von Reporting-Anforderungen
roskakori
 
Ad

Recently uploaded (20)

PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PDF
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PDF
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
 
The Growing Value and Application of FME & GenAI
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 

Helpful pre commit hooks for Python and Django

  • 2. What is pre-commit? ● A framework to manage git pre-commit hooks. ● To perform quality check on code before accepting a commit. ● Many handy hooks available through it. ● Helps you catch many (often minor issues) before they make it into the repository.
  • 3. How to get pre-commit ● Visit https://pre-commit.com/ ● Various methods to install: – Plain Python: pip install pre-commit – Anaconda: conda install -c conda-forge pre-commit – Ubuntu: sudo apt-get install pre-commit – MacOS: brew install pre-commit
  • 4. Configuration ● Add a file “.pre-commit-config” ● Add the github repositories and hooks you want to run before each commit. ● Example: ● Run “pre-commit install” ● Hooks are checked on “git commit ...” and commit in IDE ● Manually run hooks using “pre-commit run --all-files” exclude: "^.idea" repos: - repo: git://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: mixed-line-ending args: ["--fix=auto"]
  • 5. Configuration ● Add a file “.pre-commit-config” ● Add the github repositories and hooks you want to run before each commit. ● Example: exclude: "^.idea" repos: - repo: git://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: mixed-line-ending args: ["--fix=auto"] Regex for files and folders not to check Source code repository and version of hooks to use Hooks to use Parameters for a specific hook
  • 6. Standard hooks – Text files ● - repo: git://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 ● trailing-whitespace: remove white space at end of line in text files ● mixed-line-ending: detect or fix mixed line endings (e.g developers on Windows and Unix working on same code) ● end-of-file-fixer: Ensures that text files end with a newline character.
  • 8. Standard hooks – Unwanted files ● check-byte-order-marker: rejects text files starting with UTF-8 BOM (as created by various Microsoft tools like Notepad, causing many Unix tools to fail) ● check-added-large-files: rejects large files; possibly specify what is large: args: ["--maxkb=768"] ● Check-merge-conflict: refuse to commit before all merge conflicts are resolved
  • 9. Standard hooks - Python ● check-ast: check Python syntax ● requirements-txt-fixer: sorts entries in requirements.txt ● debug-statements: refuse to commit calls to breakpoints() and imports of debugger
  • 10. Standard hooks – Syntax checks ● check-json ● check-toml ● check-xml ● check-yaml
  • 11. Pretty print Python ● Using black (opinionated): https://github.com/psf/black ● Configure using pyproject.toml - repo: https://github.com/ambv/black rev: stable hooks: - id: black [tool.black] line-length = 120 include = '.pyi?$' exclude = ''' /( .eggs | .git | venv | build | dist )/ '''
  • 12. Sort imports consistently ● Using isort: https://github.com/timothycrosley/isort ● Configure using setup.cfg ● Can be tricky to work with black → see example to the right - repo: https://github.com/timothycrosley/isort rev: 5.4.2 hooks: - id: isort [tool:isort] # Use project line length. line_length = 120 # Packages from own projetc default_section = THIRDPARTY known_first_party = mytool, niftysite # Use same style as black. force_grid_wrap=0 include_trailing_comma = True multi_line_output=3 use_parentheses=True # Skip virtual environments. skip_glob = venv
  • 13. Flake8 – Semantic Python check ● Find unused imports, shadowed variables, string formatting, unreachable code, … ● Configure using setup.cfg - repo: https://gitlab.com/pycqa/flake8 rev: 3.8.3 hooks: - id: flake8 [flake8] max-line-length = 120 ignore = E203, W503 exclude = .git build dist venv docs/conf.py
  • 14. Prettier – Pretty print various formats for web development ● Supports JavaScript, CSS, Markdown, HTML, GraphQL, YAML and others by means of plugins ● Does not work with Django HTML templates → exclude using “.prettierignore” (uses same format as .gitignore) - repo: https://github.com/prettier/prettier rev: 2.0.5 hooks: - id: prettier **/coverage.xml **/templates/**/*.html
  • 15. Summary ● Pre-commit is easy to install and configure. ● Solves minor minor issues arising when multiple developers work on the same code. ● Plenty of available hooks.