[Python] Using pre-commit to improve Code Readability Easily


Posted by jerryeml on 2024-04-13

Environment

Python 3.8.1
pre-commit 2.21.0

Python Coding Style

We use pre-commit that includes Black, flake8 and pep8-naming to do code formatting and style check.

    pip install pre-commit

設定 .pre-commit-config.yaml

pre-commit 是在執行 git commit 指令時會跟著運作的指令,所以必須在 git 專案中添加 .pre-commit-config.yaml 設定檔,讓 pre-commit 知道要執行哪些 hooks 。

所以 .pre-commit-config.yaml 設定檔會跟 .git/ 同一層,例如:

.
├── README.md
├── requirements.txt
├── .git
├── .pre-commit-config.yaml
└── project/

repos:
  # - repo: https://github.com/psf/black
  #   rev: 22.6.0
  #   hooks:
  #     - id: black
  #       # It is recommended to specify the latest version of Python
  #       # supported by your project here, or alternatively use
  #       # pre-commit's default_language_version, see
  #       # https://pre-commit.com/#top_level-default_language_version
  #       language_version: python3
  #       exclude: ^src\\cases\\.*

  - repo: https://github.com/PyCQA/flake8
    rev: 6.1.0
    hooks:
      - id: flake8
        additional_dependencies: [pep8-naming]

How to check quality in CICD

you can use add pre-commit for verifying PEP8 in your CICD

  • Github Actions
  • Codebuild
  • Jenkins
name: CI

on:
  workflow_dispatch:
  push:
    branches: [main]
  pull_request:

jobs:
  lint-check:
    runs-on: ebf-pod-ubuntu-2004-slim@${{ github.run_id }}-lint-check

    steps:
      - uses: actions/checkout@v2

      - name: Install pre-commit
        run: pip install pre-commit

      - name: Lint with pre-commit
        run: pre-commit run --all-files

Output

(.venv) jerry_he@tw-jerryhe testing-case (WS-999-fixed-coding-style) $ pre-commit run --all-files
flake8...................................................................Passed

完美Pass囉


#Python #CICD #pep8







Related Posts

[Linux] Docker疑難雜症

[Linux] Docker疑難雜症

JavaScript 變數型態判斷及賦值

JavaScript 變數型態判斷及賦值

Sequlize & Express. P1

Sequlize & Express. P1


Comments