Background

這篇主要簡單的紀錄一下如何用 Black 來使得你的 Python 程式碼符合 PEP 8 的 coding style。

Installation

$ pip3 install black

Start

使用上起來也非常簡單,black 指令後面加上你想要 reformat 的檔案即可。

$ black run.py
All done! ✨ 🍰 ✨
1 file left unchanged.

$ black my_package/
reformatted /Users/matt/projects/my_package/some_file.py
All done! ✨ 🍰 ✨
1 file reformatted, 107 files left unchanged.

Black in Continuous Integration (CI)

Black 如何跟 CI 做結合呢? 其實很簡單 只要加上 --check 這個 option 即可。

$ black --check my_package/
would reformat /Users/matt/projects/my_package/some_file.py
All done! 💥 💔 💥
1 file would be reformatted, 107 files would be left unchanged.

Black as a Git pre-commit hook

我自己是習慣在 git commit 時 check 整個 repository 中 .py 的檔案有沒有沒通過 Black 的檢查的,以下紀錄一下怎麼達成。

install

$ pip install pre-commit

setting

接著我們需要設定 .pre-commit-config.yaml 的檔案,以確保 git 可以透過這個檔案來檢查。

.pre-commit-config.yaml

repos:
  - repo: https://github.com/ambv/black
    rev: stable
    hooks:
    - id: black
      language_version: python3.7

設定完之後,在我們每次 commit 時 black 都會檢查我們的程式碼:

$ git commit
black....................................................................Failed
hookid: black

Files were modified by this hook. Additional output:

reformatted my_package/some_file.py
All done! ✨ 🍰 ✨
1 file reformatted.

更多 pre-commit-hooks 的相關資訊可以到下列網址參考:

https://github.com/pre-commit/pre-commit-hooks/blob/master/.pre-commit-config.yaml

Reference