在程序開發時候一套好的開發環境和工具棧,能夠幫咱們極大的提升開發的效率,避免把大量時間浪費在周邊雜事上。本文以Python爲例,教你們如何快速打造完美的Python項目開發環境:內容涵蓋了模塊依賴管理、代碼風格管理、調試測試管理和Git版本管理,使用git hook作項目規範檢查等。python
Pipx是一款跨平臺的Python環境隔離管理工具,能夠在支持在 Linux、Mac OS 和 Windows 上運行。Pipx默認在是我的用戶下創建虛擬Python環境,並以此創建實現徹底隔離的Python運行環境。安裝pipx須要Pthon 3.6及以上版本:git
python3 -m pip install --user pipx
python3 -m pipx ensurepath
升級Pipx使用:github
python3 -m pip install -U pipx
Pipenv會自動爲你的項目建立和管理虛擬環境,以pipfile文件方式方式管理項目的依賴包,支持包的安裝和卸載。和requirements.txt不一樣,pipfile是TOML格式,支持開發環境與正式環境,還可使用Pipfile.lock鎖定環境版本。pipxenv的安裝可使用pipx:django
pipx install pipenv
有些發行版也是能夠直接經過其包管理器安裝的:編程
好比MacOS能夠下可使用:json
brew install pipenv
一個pipfile的示例以下:vim
Pipfile.lock的示例部分以下:cookie
代碼格式的統一不光能夠給咱們一個愜意的代碼格式,並且能夠避免因爲開發人員之間的代碼風格差別致使的溝通和協做問題。框架
Black就是用來格式化Python代碼的程序。它能夠自動幫咱們對代碼格式進行調整和統一,提升代碼效率和可讀性。並且經過Black減少代碼風格的差別,能夠極大提升團隊進行代碼審查的效率。async
一個Black格式化示例以下:
原始代碼:
def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, 'w') as f:
...
格式化後的代碼:
def very_important_function(
template: str,
*variables,
file: os.PathLike,
engine: str,
header: bool = True,
debug: bool = False,
):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, "w") as f:
...
Python開發中常常須要import第三方的模塊,每每這部分代碼混亂不堪,使用isort能夠則能夠美化這部分的代碼。 isort能夠按字母表順序對import進行排序,自動分紅多個部分。
咱們可使用pipenv安裝black 和isort:
pipenv install black isort -dev
isort的效果示例,能夠看下面的動圖:
Black和isort同時使用時,二者默認配置不兼容,咱們須要覆蓋isort配置,優先以Black的格式化爲準。能夠經過setup.cfg文件並添以下配置來完成該任務。
[isort]
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True
line_length=88
Flake8能夠用來確保代碼遵循PEP8中定義的標準Python編程約定,是Python官方輔助代碼風格檢測工具,lake8檢查規則靈活,支持集成額外插件(好比vim、sublime、PyCharm、vsc等都有其相關插件),擴展性強。
其安裝也可使用pipenv:
pipenv install flake8 –dev
flake8的使用示例以下:
flake8 example.py的檢查結果:
flake8默認會忽略一些約定(E,F),若是咱們檢查全部約定:
flake8 --select E,F example.py,結果:
和isort同樣,爲了配合兼容Black,須要在setup.cfg中額外配置:
[flake8]
ignore = E203, E266, E501, W503
max-line-length = 88
max-complexity = 18
select = B,C,E,F,W,T4
Mypy是Python的可選靜態類型檢查器,能夠用結合動態(或"鴨子")類型和靜態類型優勢其餘代碼的性能。經過Mypy將Python的動態類型便捷性和表現力的優點與靜態類型強系統和編譯時類型檢查相結合,而且生成原生代碼,支持經過Python VM運行,能夠沒有運行時開銷的高性能運行。在Python中使用靜態類型好處有:
可使程序更易於理解和維護;
能夠幫助編譯時調試和發現錯誤,減小測試和調試。
能夠在代碼部署到生產環境以前就能夠找到難以捕捉的錯誤。
可使用pipenv直接安裝Mypy:
pipenv install mypy –dev
mypy動態類型和靜態類型一個示例以下:
默認狀況下,Mypy會遞歸檢查全部類型註釋的導入,這會致使庫不包含這些註釋時出錯。須要修改mypy配置僅檢查當前代碼運行,並忽略沒有類型註釋的import模塊。這也能夠在setup.cfg中設置:
[mypy]
files=項目,test
ignore_missing_imports=true
程序開發中,除了寫代碼外,另一個重要的部分是單元測試。Python測試方面咱們要介紹的工具備pytest。
可使用pipenv添加測試工具包及擴展:
pipenv install pytest pytest-cov --dev
Pytest框架可讓編寫小測試變得容易,並且支持以擴展的方式提供更加複雜的功能。下面是pytest網站的一個簡單示例:
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
經過如下命令測試
pipenv run pytest
結果以下:
pytest-cov是pytest的單元測試行覆蓋率的插件。pytets-cov的測試結果示例以下:
pytest還有不少的擴展插件:
pytest-cov: 單元測試覆蓋率報告
pytest-django: 對Django框架的單元測框架
pytest-asyncio:對asyncio的支持
pytest-twisted: 對twisted框架的單元測框架
pytest-instafail: 發送錯誤時報告錯誤信息
pytest-bdd 測試驅動開發工具
pytest-konira 測試驅動開發工具
pytest-timeout: 支持超時功能
pytest-pep8: 支持PEP8檢查
pytest-flakes: 結合pyflakes進行代碼檢查
更多插件能夠查看github pytest-dev組織下的項目。
項目中,全部的測試都應該放在test目錄中,我須要給setup.cfg添加配置:
[tool:pytest]
testpaths=test
單元覆蓋率的項目配置須要建立一個新文件.coveragerc返回應用程序代碼的覆蓋率統計信息,配置示例以下:
[run]
source = 項目
[report]
exclude_lines =
pragma: no cover
def __repr__
if self\.debug
raise AssertionError
raise NotImplementedError
if 0:
if __name__ == .__main__.:
而後再工程中運行一下命令,測試項目的覆蓋率
pipenv run pytest --cov --cov-fail-under =100
若是程序代碼的測試覆蓋率低於100%,就會報錯。
Git hook可讓咱們在提交或推送時執行檢查腳本,腳本能夠配置對項目鏡像測試或者規範性檢查。運行腳本。咱們能夠配置pre-commit hook容許輕鬆配置這些鉤子,下面.pre-commit-config.yaml配置示例能夠幫咱們自動作代碼規範化,包括isort檢查、black檢查、flake8檢查、mypy靜態類型檢查、pytest測試、pytest-cov測試覆蓋率檢查:
repos:
- repo: local
hooks:
- id: isort
name: isort
stages: [commit]
language: system
entry: pipenv run isort
types: [python]
- id: black
name: black
stages: [commit]
language: system
entry: pipenv run black
types: [python]
- id: flake8
name: flake8
stages: [commit]
language: system
entry: pipenv run flake8
types: [python]
exclude: setup.py
- id: mypy
name: mypy
stages: [commit]
language: system
entry: pipenv run mypy
types: [python]
pass_filenames: false
- id: pytest
name: pytest
stages: [commit]
language: system
entry: pipenv run pytest
types: [python]
- id: pytest-cov
name: pytest
stages: [push]
language: system
entry: pipenv run pytest --cov --cov-fail-under=100
types: [python]
若是你須要跳過這些鉤子,你能夠運行git commit --no-verify或git push --no-verify
上面咱們提到Python項目應該具有的工具集和配置,能夠將其做爲模版。cookiecutter的模版定義範例以下:
cookiecutter.json
{
"full_name": "Chongchong",
"email": "chongchong@ijz.me",
"project_name": "Python-Practice",
"repo_name": ""Python-Practice ",
"project_short_description": "The Simple Python Development Practice Example.",
"release_date": "2019-09-02",
"year": "2019",
"version": "0.0.1"
}
而後使用cookiecutter自動生成整改工程:
pipx run cookiecutter Python-Practice
cd Python-Practice
git init
安裝依賴項
pipenv install --dev
運行 pre-commit和pre-push hook:
pipenv run pre-commit install -t pre-commit
pipenv run pre-commit install -t pre-push
本文咱們介紹了在Python項目開發時候必需要具有的一些開發測試檢查工具。經過這些能夠自動生成Python項目,代碼風格檢查、代碼測試等操做,能夠幫助咱們打造一個高效完美的Python開發環境。