How to force Python syntax in pre-commit?
How to force variable and function names and follow Python PEP 8 style in git pre-commit?
I'm working in a Django project and I want to force developers to write code following the PEP 8 style for variables and function, preventing CamelCase
in variable name like this example:
class MyModel(models.Model):
roomName = models.CharField()
roomNumber = models.CharField()
That is, I would like this declaration to be forced by git to have the following syntax:
class MyModel(models.Model):
room_name = models.CharField()
room_number = models.CharField()
In the case of functions, instead of:
def checkRules()...
it would be something like:
def check_rules()...
I have this .pre-commit-config.yaml
but some bad code is passing and if we can force good practice in pre-commit that would be great.
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
args: ["--line-length", "120"]
- repo: https://github.com/PyCQA/flake8
rev: 7.1.0
hooks:
- id: flake8
additional_dependencies: []
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
args: ['--order-by-type', "--profile", "black", "--filter-files"]
name: isort (python)
- id: isort
name: isort (cython)
types: [cython]
- id: isort
name: isort (pyi)
types: [pyi]
The following is the base configuration I'm using in several of my repos.
You can run the pre-commit run --all-files
command to check file formatting inside the project. To automatically run this on every commit, install it as a git hook with pre-commit install
.
Example for .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-json
- id: debug-statements
- id: detect-private-key
- id: requirements-txt-fixer
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
args: ["--line-length", "120"]
- repo: https://github.com/pycqa/flake8
rev: 7.1.0
hooks:
- id: flake8
additional_dependencies:
- flake8-naming
- flake8-django
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
Example for .flake8
[flake8]
max-line-length = 120
exclude = migrations, .venv, .git, __pycache__
format = pylint
Example for .github/workflows/pre-commit.yml
name: Run pre-commit checks
on:
push:
branches:
- main
pull_request:
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.12
- name: Install dependencies
run: |
pip install pre-commit
pre-commit install
- name: Run pre-commit
run: pre-commit run --all-files
NB: You need to add pre-commit
lib to your requirements.
NB: For Django HTML templates and CSS formatting I'm using djlint
manually.