# Python Linter & Formatter

Python 程式碼檢查器與格式化

#### Linter

##### 什麼是 Linter

Linter 或 lint，主要功能是對程式進行靜態分析——在程式未執行情況下檢查出潛在的語法錯誤。

> Linter，就是協助你檢查程式語法正確性的工具，大部分程式語言都有屬於自己的 linter，而 Python 最常見的 linter 不外乎pylint、pep8（現為 pycodestyle） 和 flake8。

上述 linter 都是 Python 的 package，同時也是 CLI 工具，皆可透過命令列，獨立執行與使用。

除了語法正確性，linter 還會檢查**排版風格**，比如程式碼是否符合 [**PEP 8**](https://peps.python.org/pep-0008/) 要求的排版風格，也是上述 linter 檢查的一環，如此才有「排版風格一致」可言。換句話說，所謂的一致，原則上指的是與 [**PEP 8 規範**](https://peps.python.org/pep-0008/)一致。

##### Flake8 Linter

- GitHub: [https://github.com/PyCQA/flake8](https://github.com/PyCQA/flake8)
- Doc: [https://flake8.pycqa.org/en/latest/](https://flake8.pycqa.org/en/latest/)
- [VS Code 設定 Python Linter、Formatter 教學 - Code and Me](https://blog.kyomind.tw/flake8-yapf-setting/)

#### Formatter

##### 什麼是 Formatter

統一程式碼排版風格第一步是使用 linter，通用型 linter 會檢查（但不限於）程式碼風格上所有違反 PEP 8 的部分，發現風格不符後，接著就要用 formatter（格式化器）進行格式化！

換句話說，formatter 就是**自動幫你修正這些排版問題的工具**！而這個過程，就是「**格式化**」。

程式語法錯誤——比如使用未設定的變數——雖然也可能被 linter 檢測出並提示，但這部分的修正通常得手動為之。Formatter 只能協助處理排版風格上的缺失。

雖然修正排版一樣也可以手動為之，但是一來麻煩，二來難免會有遺漏，還是靠機器比較實在，也輕鬆得多。

##### Black Formatter

- GitHub: [https://github.com/psf/black](https://github.com/psf/black)
- Doc: [https://black.readthedocs.io/en/stable/index.html](https://black.readthedocs.io/en/stable/index.html)
- [Python Flake8 與 Black Formatter 擴充套件快速上手 - Code and Me](https://blog.kyomind.tw/flake8-and-black/)
- [使用 Black 格式化程式碼——《Python 功力提升的樂趣》 - Code and Me](https://blog.kyomind.tw/beyond-the-basic-stuff-with-python-01/)

##### Ruff Formatter

- GitHub: [https://github.com/astral-sh/ruff](https://github.com/astral-sh/ruff)
- Doc: [Ruff](https://docs.astral.sh/ruff/)